[CPP] Multiple Inheritance

Multiple Inheritance

  • In Java you can implement multiple interfaces but only extend one class
  • In C++ you can inherit from(extend) multiple classes
  • You will inherit all of the behaviour(i.e. function implementations), not just the interface.
  • But be careful of multiple inheritance, because
    • there are dangers, and confusing elements
    • there may be easier ways(e.g. composition)

There are multiple ways to support reuse of classes by new classes

Composition/Aggregation
  • Models the “has a” or “is a part of” relationship
  • Composition is a stronger form
    enter image description here
    • You need to expose the methods manually because they are on component objects
Inheritance
  • “is a” or “is a type of”
  • ImplementationL Make the “type of” a sub-class
    enter image description here
enter image description here

Don’t use C-style casting to keep the code short!

  • Use static_cast or dynamic_cast
  • Dynamic cast will check(at runtime) that the pointer really is to an object of that type
  • If you cast pointers or references when multiple inheritance is being used, then addresses may change
  • Normally, casting a pointer just changes the type, but leaves the address unchanged
  • If you go to or from a second base class, the address will change
  • If you go back to sub-class, the pointer value changes back again(use dynamic cast if necessary, to check the type)
Uses/Association
  • Implementation: Maintain a pointer or reference between them, to get to the other object

Multiple inheritance with common base classes

enter image description here

Multiple inheritance with virtual base classes

enter image description here

Dangers

  • Be aware of:
    • Inheriting the same names from multiple base classes
    • Inheriting the same base class twicem through two different intermediate classes
  • To resolve the problem:
    • Use scoping operator :: to dis-ambiguate
    • Or use virtual base classes, to keep one copy
    • Or ensure that only one base class has any data, or any non-abstract methods

Wait…What is abstract method in C++?(Pure-virtual functions)

enter image description here

评论

此博客中的热门博文

[MLE] Linear Classification

[AIM] MetaHeuristics

[CS231] Neural Networks