Initialization of a Virtual Base Class.

In a Inheritance hierarchy including virtual base classes, for ex:

A
/ \ (virtual inheritance of B,C)
/ \
B C
\ /
\ /
D

class A{};
class B : virtual public A{};
class C : virtual public A{};
class D : public B, public C{};


Since the A base class occurs twice in class C, how is it ensured that its initialized or contructed only once, and not twice ( via B's and C's ctor )?

Answer:*

In this case, class D (the most derived class) can make direct calls to the ctor of its super base class A (which is not allowed in cases not involving virtual inheritance ). If this is not done, then the default ctor of class A will be called and then the ctors of B and C are called.


1 class A
2 {
3 public:
4 A(int a){}
5 A(){}
6 };
7 class B : virtual public A{};
8 class C : virtual public A{};
9 class D : public B, public C{
10 public:
11 D():A(1),B(),C(){}
12 };
13
14 int main()
15 {
16 D d;
17 }

If the inheritance was not virtual, then D's ctor cannot access A's ctor.



No comments: