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 execution of this program, it will print "55fun". What happened to constructor calls in class Pochodna1 and Pochodna2 - are they ignored? Why member 'x' of class Bazowa is set to '55', but not '101' or '103'?
Virtual base constructors are always called from the final leaf class. None of the other constructors for the virtual base are called. In your case SuperPochodna()
is calling Bazowa()
and the calls to Bazowa(int)
in Pochodna1
and Pochodna2
are not used.
See http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.14 or just google "virtual base constructor".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With