-2

This is the code I got from the internet... and how virtual keyword is working? i think this virtual keyword has something to do with this behaviour but I don't understand what it is.

class A {
    int x;

public:
    A(int i) { x = i; }
    void print() { cout << x; }
};

class B : virtual public A {
public:
    B()
        : A(10)
    {
    }
};

class C : virtual public A {
public:
    C()
        : A(10)
    {
    }
};

class D : public B, public C {
};

int main()
{
    D d;
    d.print();
    return 0;
}
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
Ayu91
  • 27
  • 4

2 Answers2

2

why am I able to call grandparent method with grandchild object?

Because that is how inheritance works. That member function was inherited by the child class and the grand child.

I read that it was not possible

Either what you read is wrong or you misunderstood it.

how virtual keyword is working?

When a virtual base occurs multiple times in a hierarchy, those occurrences are combined into a single base sub object.

In the case of D, the base A of B and the base A of C are the same base which would not be the case if the inheritance wasn't virtual.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

You can be right in your assumption, but it is not that easy.

print is declared as a public member function. Since you derive every class with public, you still can call print from your D class object.

If you desire your described behaviour, one way is, you have to rewrite your class

class A {
    int x;

public:
    A(int i) { x = i; }

private:
    void print() { cout << x; }
};

You should study the topic of 'inheritance'. You can start with that ARTICLE.


In general a diamond class structure points to bad software design. Yeah there may be some good reasons to create something like that. But judging the type of the question, you should really forget about that and avoid it. Unless you are really sure about what you are doing.

The structure you found is described here.

skratchi.at
  • 1,151
  • 7
  • 22