简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM