0

In the following code the Multi Path Inheritance was resolved by using Virtual Class How did the constructor work? A Constructor cannot be inherited or virtual or static.

/*Multi Path Inheritance*/

class A{

public:
    int a;
    A(){
        a=50;
    }
};


class B:virtual public A{

public:
    /*B(){
        a = 40;
    }*/

};

class C:virtual public A{

public:
    /*C(){
        a = 30;
    }*/

};

class E:virtual public A{

public:
    E(){
        a = 40;
    }

};

class D : public B, public C, public E{

public:
    D(){
        cout<<"The value of a is : "<<a<<endl;  
    }

};

int main(int argc, char *argv[]){

    D d;
    return 0;
}
Nathan
  • 674
  • 8
  • 22

2 Answers2

2

Base on following quota from standard 12.6.2/10, so the constructor body will be called in following orde: A->B->C->D, so the final value of a will be 40.

In a non-delegating constructor, initialization proceeds in the following order:

 — First, and only for the constructor of the most
   derived class (1.8), virtual base classes are initialized in the order
   they appear on a depth-first left-to-right traversal of the directed
   acyclic graph of base classes, where “left-to-right” is the order of
   appearance of the base classes in the derived class
   base-specifier-list. 

 — Then, direct base classes are initialized in
   declaration order as they appear in the base-specifier-list
   (regardless of the order of the mem-initializers). 
Community
  • 1
  • 1
ZijingWu
  • 3,350
  • 3
  • 25
  • 40
1

You can find a lot of informations and examples about virtual inheritance here (yes, it's actually on msdn, how strange :) )

As for the constructors, constructors get called as you specify them. If you don't specify a call for a virtua-base class constructor,

constructors for virtual base classes anywhere in your class's inheritance hierarchy are called by the "most derived" class's constructor.

(read it here).

Stefano Falasca
  • 8,837
  • 2
  • 18
  • 24