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.
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.