Gcc 4.5.1 virtual inheritance problem

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)

+6
source share
2 answers

This is a compiler error. I also tested GCC 4.2.1 and the result was 8 cases.

+1
source

I tested several older flavors (up to 4.3 - which work) - you don't have series 4 (to check in the morning), but I agree, this seems like a mistake (and not in dB), it's probably worth raising it.

I noticed that if you change the first relation (from Base1 to God from virtual to non-virtual), then the example works as expected. I suppose it depends on your needs, regardless of whether you will directly call ctor God from the most derived class (although I have never seen this approach before ...)

+1
source

Source: https://habr.com/ru/post/907992/


All Articles