I'm trying to grasp the role of virtual inheritance in multiple inheritance and polymorphism. I have three classes: A, B, and C. A is the base of B and C. B is the (abstract) base of C. I chose to call this the "dreaded triangle problem" because it involves only three classes, rather than four.
1 2 3 4 5
|
A
| \
| B (abstract)
| /
C
|
A may be instantiated by itself when it
is not a B. C may be instantiated, and it
is an A and B. This part is key: B
is an A -- B must inherit from A because B must use A's members and methods. Anything that
is a B must also
be an A.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class A {
public:
foo();
}
class B: public A {
public:
bar(); //depends on A::foo()
protected:
B(); //protected constructor (abstract class)
}
class C: public A, public B {
public:
baz();
}
|
The first solution that comes to mind is "C need not inherit from A, because it will indirectly inherit from A by virtue of inheriting from B." This may be acceptable for this very case, but what if C also inherits from another class which inherits from A? This might be a separate issue, because it would create a diamond problem (in contrast to the above illustrated "triangle problem").
Questions:
1. I understand that the keyword "virtual" preceding a base class declaration prevents a subobject from being created for that base class. What is the context of this rule? Does this mean all base classes, that are marked "virtual" along the hierarchy of the instantiated object's class, will share the same one subobject per class? What about non-virtual base classes, do each of those summon a unique subobject per base class declaration, in addition to each "shared" virtual-inherited base class?
2. In the example illustrated above, where should "virtual" appear?
class C: virtual public A, virtual public B?
class C: public A, virtual public B?
class B: virtual public A?
Something else?
3. Was I correct in guessing that C should
not inherit directly from A? This could cause a diamond problem later on, but it may be an acceptable solution to the "triangle problem".