2

C++11 standard provides a way to inherit constructors from the base class. My question is regarding earlier standards. Suppose I inherit constructors in the following way:

class Base {

public: 
  Base() {};
  Base(int b) { a = ++b;}
  virtual int foo() {return 0;}
  int a;

};

class A : public virtual Base {

public: 
  A() {}
  A(int b): Base(b) {} 
  int foo() {return a*a;}

};

class C : public A {
public: 
  C() {}
  C(int b ): A(b) {}
  int foo() { return (a*a + a);}

};

Note that I am having virtual inheritance of the Base class. Now when I try to initialize a pointer to an object of type C then instead of calling Base(b) constructor, the code ends up calling Base() constructor. Here is the main function that I used:

int main(){

  C *c = new C(5); 
  std::cout << c->Base::a << std::endl;
}

The output value of "a" is 0. However, when I remove the virtual keyword while inheriting the Base class, then Base(b) constructor is called and the value of "a" is 6. Can someone help me in understanding what is going on? Why is it that with virtual inheritance default constructor is called?

SvSharma
  • 159
  • 1
  • 5

1 Answers1

6

Virtual base classes are initialised based on the member initialiser list of the constructor of the most derived class.

In your case, when you're creating an instance of C, its Base subobject will be initialised based on the member-initialiser list in C's constructor; and since Base is not listed there, it will be default-initialised.

If you were creating an instance of A, then indeed A's member-initialiser list would be used.

So to call the Base constructor which you want, you'd have to modify C's constructor like this:

C(int b ): A(b), Base(b) {}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455