Pregunta

Lets say we got a diamond inheritance where D inherit from both B1 and B2 whose base are V as follows:

struct V { 
    V(){cout << "V()" << endl;}
    V(int){cout << "V(int)" << endl;}
}; 
struct B1 : virtual V {
    B1(){cout << "B1()" << endl;}
    B1(int i): V(i) {cout << "B1(int)" << endl;
        /*…*/ }
};
struct B2 : virtual V {
    B2(){cout << "B2()" << endl;}
    B2(int i) { cout << "B2()" << endl; }
};
struct D : B1, B2 {
    D(int i): V(i) { cout << "D(int)" << endl; }
};

when I initialize D* parameter, I expect that B1 and B2 default Constructors to call V constructor. However when I ran the next line, V was called once. Why?

D* d = new D(1);

Thanks in advance.

¿Fue útil?

Solución

The constructor for a virtual base is always called just once, from the most derived class; that's just how it works. It wouldn't make sense to construct the base more than once.

Try adding a parameter to the base constructor and see what happens.

Otros consejos

The base class V is called once because V1 and V2 inhert virtualy from V. If you hasn't the possibility to inhert virtualy a problem will occure: for example if I call a method of base class from a derived the compiler cannot know which base class call, that one constructed from V1 or the other constructed from V2.

So virtual inheritance give us the possiblity to have the diamond inehritance without this issue.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top