Why is only the default base constructor called in the virtual multiple inheritance database?

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

 Base::Base(std::string) A::A() B::B() 

But I get the following output:

 Base::Base() A::A() B::B() 

Why is the default Base constructor 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
source share
1 answer

The virtual base is built using the most derived object. Therefore, the AB constructor calls the Base constructor, but since you did not specify a constructor for AB , its default constructor simply calls the default constructor of Base .

You can call the string constructor from AB as follows:

 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 setting!

+4
source

Source: https://habr.com/ru/post/1487860/


All Articles