Multiple virtual inheritance and calling the base class constructor

There is this code:

#include <iostream> class Bazowa { int x; public: Bazowa() : x(55){} Bazowa(int x_) : x(x_) {} void fun() { std::cout << x << "fun\n"; } }; class Pochodna1 : virtual public Bazowa { public: Pochodna1() : Bazowa(101) {} }; class Pochodna2 : virtual public Bazowa { public: Pochodna2() : Bazowa(103) {} }; class SuperPochodna : public Pochodna1, public Pochodna2 { public: SuperPochodna() : {} }; int main() { SuperPochodna sp; sp.fun(); // prints 55fun return 0; } 

After executing this program, it will print “55fun”. What happened to the design challenges in the Pochodna1 and Pochodna2 classes - are they ignored? Why is the 'x' member of the Bazowa class set to '55' but not '101' or '103'?

+6
source share
1 answer

Virtual base constructors are always called from the final leaf class. None of the other constructors for the virtual database are called. In your case, SuperPochodna() calls Bazowa() , and calls to Bazowa(int) in Pochodna1 and Pochodna2 not used.

See http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.14 or simply "Google Virtual Database Designer".

+9
source

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


All Articles