Sachin Sabbarwal
Sachin Sabbarwal

Reputation: 143

c++ multiple inheritence constructor calling

In the following lines class A is the base class, inherited by classes B and C. Class D inherits from both B and C. Furthermore, the constructor in D calls constructors of B, C and A. Because when B and C inherit A as virtual, they are not eligible to call constructor of A directly (as the call to same must be made through 3rd generation).

My question is, if I want to make an object of class B, then as A is inherited virtually, is there anyway to call constructor of A (to pass v1 and v2, the variables to be used for initialization)?

class A {
   int a1,a2;
   A() {
   }

   A(int v1,v2) {
      a1 = v1;
      a2 = v2;
   }
};

class B:virtual public A {
   int b1,b2;
   B() {
   }

   B(int v1,v2) {
      b1 = v1;
      b2 = v2;
   }
};

class C:virtual public A {
   int c1,c2;
   C() {
   }

   C(int v1,v2) {
      c1 = v1;
      c2 = v2;
   }
};

class D:public B,public C {
   int d1,d2;
   D() {
   }

   D(int v1,v2):B(v1,v2),C(v1,v2),A(v1,v2)
   {
      d1 = v1;
      d2 = v2;
   }
};

Upvotes: 0

Views: 142

Answers (2)

RAB
RAB

Reputation: 75

What you can do is to make classes B and C inherit normally (without keyword 'virtual') from A, but make class D to inhert virtually from B and C. That will allow you to create object of class B (or C) by passing values for class A constructor>

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477060

It's perfectly fine to also give B an initializer for A. All that virtual inheritance means is that if you have an even-more-derived object, then the virtual base is constructed by the most-derived object. But if you're only constructing an instance of B, then that instance is the most derived object. So just write it like this:

 class B : public virtual A
 {
 public:
     B() : A(1, 2) {  }
     // ...
 };

It's only when you derive from B that the base initializer is ignored.

Upvotes: 1

Related Questions