ssg
ssg

Reputation: 347

Not able to understand virtual base class constructor in case of multilevel inheritance

In below program in case if I change the sequence in Derived class "D" then I am getting different order of the constructors of base class.

    #include <iostream>

    using namespace std;

    class A {
      public :
            A ()
            {
                cout << "A()" <<endl;
            }
    };

    class B : virtual A{
      public :
            B ()
            {
                cout << "B()" << endl;
            }
    };

    class C : virtual B{
      public :
            C ()
            {
                cout << "C()" << endl;
            }
    };

Case (1)
========
    class D : public A, public B, public C
    {

    };

    int main()
    {
        D d;
        return 0;
    }
OUTPUT : 
A()
B()
A()
B()
C()

Case (2)
========
    class D : public C, public B, public A
    {

    };

    int main()
    {
        D d;
        return 0;
    }
OUTPUT :
A()
B()
C()
B()
A()

Case (3)
========
    class D : public B, public A, public C
    {

    };

    int main()
    {
        D d;
        return 0;
    }
OUTPUT :
A()
B()
B()
A()
C()

Please can anyone tell how constructors are called in case of virtual class concepts.

Upvotes: 3

Views: 113

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

Please can anyone tell how constructors are called in case of virtual class concepts.

According to the initialization order, the virtual base class will be initialized at first.

1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed

In all the 3 cases, class D is inheriting from A, B, and C, there're two virtual base classes in D, i.e. A inheritted via B and C, and B inheritted via C. And A will be initialized firstly because it's the most base class, so for all the 3 cases A() and B() will be printed out at first.

After that the direct base classes will initialized in left-to-right order. For the 1st case they'll be A() B() C(), for the 2nd case they'll be B() C() A(), for the 3rd case they'll be B() A() C().

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119069

The virtual bases are always initialized first in DFS post-order. This guarantees that the virtual A and B bases will be initialized first, and A before B since B is derived from A. After that, the three non-virtual bases A, B, C are simply initialized in declaration order as you would expect.

Upvotes: 0

Related Questions