Start with a snippet of code:
#include <iostream> struct God{ God(){_test = 8;} virtual ~God(){} int _test; }; struct Base1 : public virtual God{ //Base1(){std::cout << "Base1::Base1" << std::endl;} //enable this line to fix problem virtual ~Base1(){} }; struct Base2 : public virtual Base1{ virtual ~Base2(){} }; struct A1 : public virtual Base2{ A1(){std::cout << "A1:A1()" << std::endl;} virtual ~A1(){}; }; struct A2 : public virtual Base2{ A2(){std::cout << "A2:A2()" << std::endl;} virtual ~A2(){}; }; struct Derived: public virtual A1, public virtual A2{ Derived():Base1(){std::cout << "Derived::Derived()" << std::endl;} Derived(int i){std::cout << "Derived(i)::Derived(i)" << std::endl;} virtual ~Derived(){} }; int main(){ God* b1 = new Derived(); std::cout << b1->_test << std::endl; //why it prints 0? God* b2 = new Derived(5); std::cout << b2->_test << std::endl; return 0; }
Compiled with GCC 4.5.1 and 4.6.1 The only difference between Derived class constructors is that the former explicitly indicates which Base1 constructor should be called. I would expect both cout in main () to print 8. Unfortunately, the first prints 0 !.
Why?
If I include the explicit definition of the Base1 constructor, it fixes the problem. If I remove virtual inheritance in the definition of the Derived class (Derived class: public A1, public A2), it also works. Is behavior expected?
Problem not observed in GCC 3.4.4 or Microsoft Compiler (VS)
source share