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;
}
awesoon
  • 32,469
  • 11
  • 74
  • 99
Rajeev
  • 203
  • 2
  • 10
  • You are looking for this http://stackoverflow.com/questions/4384765/whats-the-difference-between-pretty-function-function-func . – Varvarigos Emmanouil Jun 24 '13 at 10:49
  • Because the constructors of virtual base classes are called from the most derived class. In your example, what argument do you expect `Base::Base( std::string )` to receive? – James Kanze Jun 24 '13 at 10:48
  • This makes sense. As in virtual base class we are going to have just one shared object, so which class ( A or B ) should construct it as they are passing different string to the constructor. If most derived class is constructing it, there is no confusion. – Rajeev Jun 24 '13 at 11:34

1 Answers1

5

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!

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084