T B H P N

Class Inheritance

Class Relationships:

Inheritance is one of four class relationships, doc, we use to construct Object Oriented Designs: Inheritance, Composition, Aggregation, and Using. Inheritance is an "is-a" relationship. Composition is a strong ownership or "part-of" relationship. Aggregation is also a "part-of" relationship, but is weaker than composition because it does not guarantee that the aggregated part is owned, only that it can be owned by the aggregator. Finally, using is a dependency on an object that is not part of the user, was not created by the user, and should not be destroyed by the user.
Inheritance: - Code for this example
People
  • Inheritance is a specialization or "is-a" relationship. Soldier specializes Person and Officer, Sergeant, and Private specialize Soldier.
  • Class methods may be qualifed as virtual, and may be declared to be pure virtual (using = 0).
    • Non-virtual methods should not be redefined in derived classes.
    • Virtual methods may be, but don't have to be, redefined in derived classes.
    • Pure virtual methods must be defined in derived classes because the base doesn't define them.
  • All base methods and data are inherited by its derived classes. Inherited constructors, destructors, and assignment operators are not explicitly used by the derived class unless invoked with the base class name, i.e., Person::operator= may be invoked as part of the Soldier::operator= implementation.
  • Code reuse through inheritance is useful.
  • The most important behavior is substitution. Any pointer or reference to a base instance may be replaced by a pointer or reference to any instance of a class that derives from the base. See the show(Soldier&) function for an example.

Code Example:

Virtual Function Pointer Table

Substituability:

Substitutability occurs because all classes publicly derived from the same base class share the base's member functions and so respond to the same client commands, but each in their own way.

All pointers or references of base type can be bound to an instance of any class that derives from the base. A function that accepts the base pointer or reference will invoke functions of the type of the bound instance. The mechanism that provides this behaviour is a dynamic dispatch using the Virtual Function Pointer Table (VFPT).

If an instance of derived class D is bound to a pointer of its base type B, invocations of a virtual method using the base pointer are dispatched using bindings from the VFPT, show in the diagram to the left.

Here, member function mf1 is not overridden by the derived class, so bPtr2->mf1() invokes the base's function. Member function mf2 is overridden by the derived class, so bPtr2->mf2() invokes the derived class's function.

More Details about Inheritance:

Some important examples of inheritance:

Inheritance plays a major role in building Plugins, as we will see later.
CST strip