10.1 Multiple base classes

10.1.1 Ensure that access to base class subobjects does not require explicit disambiguation

A class inherited more than once in a hierarchy, and not inherited virtually in all paths will result in multiple base class subobjects being present in instances of the derived object type. Such objects require that the developer explicitly select which base class to use when accessing members. The result is a hierarchy that is harder to understand and maintain.

class Base
{
public:
void foo ();
};
   
class Derived_left: public Base {};
   
class Derived_right: public Base {};
   
// @@- Non-Compliant: 2 subobjects for 'Base' -@@
class Derived: public Derived_left, public Derived_right
{
};
   
void test()
{
Derived d;
// ambiguous - Derived_left::Base::foo or Derived_right::Base::foo?
d.foo (); 
}

The example above can be made to comply with this rule by using virtual inheritance:

class Base {};
             
class Derived_left: public virtual Base {};
   
class Derived_right: public virtual Base {};
   
class Derived: public Derived_left, public Derived_right // @@+ Compliant +@@
{
};

References

  • HIC++ v3.3 – 3.3.15

Click here for references