4

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;
}
4

1 回答 1

5

虚拟基础是由最派生的对象构造的。所以AB的构造函数调用Base构造函数,但是由于你没有为 指定构造函数AB,它的默认构造函数只是调用 的默认构造函数Base

您可以这样调用字符串构造函数AB

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

注意构造函数A::A()B:B()不要在这个设置调用Base构造函数!

于 2013-06-24T10:48:18.640 回答