0
#include<iostream>
using namespace std;

class A
{
 protected:
 int x;
 public:
 A(int i)
  { 
    x = i;
    cout<<"A parameterized constructor called x="<<x<<endl;
  }
 void print()
  {
    cout <<"A print function called x="<<x;
  }
};

class B: virtual public A
{
  public:
  B():A(10)
  {
    cout<<"B Constructor called"<<endl;
  }
};

class C: virtual public A 
{
  public:
  C():A(20)
  {
    cout<<"C Constructor called"<<endl;
  }
};

class D: public B, public C
{
  public:
  D():A(3)
  {
    cout<<"D parametrized constructor called"<<endl;
  }
};

int main()
{
  D d;
  d.print();
  getchar();
  return 0;
}

Output

A parameterized constructor called x=3
B Constructor called
C Constructor called
D parametrized constructor called
A print function called x=3

Can someone tell me which constructors are called first in the above code?

According to the output, A's parameter Constructor is called first but how can it know the value 3 passed in D? Doesn't it should take a default value or call the default constructor instead of parameterized constructor?

  • Would you mind indenting/formatting the code correctly? I corrected the sentence structure at the end. – Guillaume Racicot Nov 07 '17 at 14:53
  • 1
    `D():A(3) {}` You call A's constructor with the value 3, no? Or I don't understand the question. – DeiDei Nov 07 '17 at 14:53
  • have a look to https://stackoverflow.com/questions/2064880/diamond-problem – OznOg Nov 07 '17 at 14:55
  • To clarify your specific problem, maybe it get more clear when you realize that if using virtual inheritance, just one object of type `A` is constructed, and that happens only one time, the value is specified by parametrized constructor `D():A(3)`, so when `B()` constructor is called, `A` was alrready constructed, so `C():A(20)` and `B():A(10)` is never called. BTW if you need to call the default constructor of `A`, use: `D():A()`, and add it to `A` class definition: `A():x(0){}` – Rama Nov 07 '17 at 15:49
  • Thanks Rama for clarification so B and C constructors never call A –  Nov 07 '17 at 15:56
  • Yes, here is a better matched duplicated question/answer: https://stackoverflow.com/questions/12500230/diamond-inheritance-lowest-base-class-constructor – Rama Nov 07 '17 at 16:16

0 Answers0