问题
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