Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple virtual inheritance and constructor call of base class

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'?

like image 436
scdmb Avatar asked Jan 28 '12 19:01

scdmb


1 Answers

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

like image 156
smparkes Avatar answered Sep 28 '22 09:09

smparkes