virtual-bases/virtual-problem.cc - Ignoring constructor in virtual base class. | Lecture 5 - slide 20 : 40 Program 3 |
// For exercise. // This program illustrates a slightly surprised construction of the A-part of a D-object. // A D object has a B-part and a C-part, in both of which we make use of our own default constructors. Both of these delegates to to A(int). // But it turns out that A(int) is NOT used in the construction of a D-object. // Surprise, probably! Please - as an exercise - consider this issue. #include <iostream> #include <string> using namespace std; class A { public: int a; A(): a(9){} A(int a): a(a){} }; class B : public virtual A { public: int b; B(): A(5), b(1){} // A(int) is ignored in the actual construction of the D-object in main. }; class C : public virtual A { public: int c; C(): A(7), c(2){} // A(int) is ignored in the actual construction of the D-object in main. }; class D : public B, public C { public: int d; D(): d(9){} // Use the default constructors of B and C }; int f(D &x){ cout << x.a << endl; // 9 // We se that The default constructor in A have been used. cout << x.B::a << endl; // 9 cout << x.C::a << endl; // 9 cout << x.b << endl; // 1 cout << x.c << endl; // 2 cout << x.d << endl; // 9 } int main(){ D d; f(d); }