Friday, November 09, 2007

C++ note: initializers in multiple inheritance

Here is a tutorial on C++ multiple inheritance.

A C++ class can inherit multiple base classes. If these base class still have base classes, they will be initialized separately by default. (For each parent class, the subclass will contain the inherited structures) For example, suppose B and C derive from A, and D derive from B and C, D will have two copies of A. One inherited from B, and the other from C.

In some occasions only one copy of A is needed in D. This type of inheritance is enabled by letting B and C virtually derive from A. By virtual inheritance, B and C no longer encompass the structure of A into their structure, but include a pointer to the A structure in their vtables. When D derive from B and C, the compiler generates only one A structure that is shared by B and C.

Here comes a question: in the constructor of D, what structures do we need to initialize?

class A {
public:
   int a;
  A ( int i ) : a (i) {}
}

class B : virtual public A {
public:
   B ( int i ) : A(i) {}
}

class C : virtual public A {
public:
   C ( int i ) : A(i) {}
}

class D : public B, public C {
   D ( int i ) : A(i), B(i), C(i) {} // <-------------
}

In the above example, D has to initilize A, B and C in its constructor. The initialization of A is mandatory even though both B and C do have the initializers in their constructor. When D is constructed, the initializers of B and C will not assign any value to A by default. This fact can be observed by removing the initialization of A in D, and printing the a field from D-object.

1 comment:

petrocket said...

Nice. That's a tricky thing to watch for when using multiple inheritance.