Why only base class default constructor is called in virtual base multiple inheritance? [duplicate]

隐身守侯 提交于 2019-12-01 05:29:17

问题


In multiple inheritance, I have a virtual Base class which is inherited by class A and class B. A and B are base classes of AB. Please see the code below. In constructor of A and B, Base(string) constructor is called. I am expecting to get following output:

Base::Base(std::string)

A::A()

B::B()

But I am getting following output:

Base::Base()

A::A()

B::B()

Why default constructor of Base is being called?

#include<iostream>
#include<string>
using namespace std;

class Base{
public:
        Base(){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
        Base(string n):name(n){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
private:
string name;
};

class A : public virtual Base {
public:
        A():Base("A"){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
private:
string name;
};

class B : public virtual  Base {
public:
        B():Base("B"){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
private:
string name;
};

class AB : public A, public B{

};

int main(){
        AB a;
}

回答1:


The virtual base is constructed by the most-derived object. So AB's constructor call the Base constructor, but since you didn't specify a constructor for AB, its default constructor just calls the default constructor of Base.

You could call the string-constructor from AB like this:

struct AB : A, B
{
    AB() : Base("hello"), A(), B() { }
};

Note that the constructors A::A() and B:B() do not call the Base constructor in this setup!



来源:https://stackoverflow.com/questions/17273524/why-only-base-class-default-constructor-is-called-in-virtual-base-multiple-inher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!