When using a virtual base class in a multiple inheritance scenario, is it necessary for all derived classes to reference the virtual base?

StackOverflow https://stackoverflow.com/questions/14288240

  •  15-01-2022
  •  | 
  •  

Pergunta

The US Air Force's JSF C++ coding standard requires that the virtual base class be declared for each derived class that accesses the virtual base.

For example, in the following hierarchy:

  A
 / \
B1  B2
C1  C2
 \ /
  D

... the rule they impose in this standard (AV Rule 88.1, for reference), requires the classes to be declared like so:

class A;
class B1 : virtual A;
class B2 : virtual A;
class C1 : B1, virtual A;
class C2 : B2, virtual A;
class D  : C1, C2, virtual A;

My questions are as follows:

  1. Is this semantically different from only inheriting virtually in the declaration @ B1/B2, and not specifying virtual A at each subsequent class declaration?
  2. If it's semantically different, why would anyone /want/ to leave it off? It seems silly to me that you'd absolutely have to do this at each layer of inheritance since that adds a potential point of failure.
Foi útil?

Solução

It semantically identical, since each derived class will have exactly one virtual base of type A. Mentio­ning the virtual base explicitly is quite nice, because the most-derived class constructs the virtual base (unlike what happens for non-virtual bases), and the construction order is important to keep in mind when writing the constructors of the derived classes.

I don't have a technical answer for (2). You don't have to do it, but it would be nice if you did. Like calling your parents, I suppose. As with many things, C++ doesn't force you to be reasonable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top