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:

People
  • Inheritance is a specialization relationship. Soldier specializes Person and Officer, Sergeant, and Private specialize Soldier.
  • Class methods may be qualifed as virtual, and may be declared to be abstract.
    • Non-virtual methods should not be redefined in derived classes.
    • Virtual methods may be, but don't have to be, redefined in derived classes.
    • Abstract methods must be defined in derived classes because the base doesn't define them.
  • Constructors, destructors, and assignment operators are not inherited. All other methods are.
  • Code reuse through inheritance is useful.
  • The most important behavior is substitution. Any reference to a base instance may be replaced by a reference to any instance of a class that derives from the base. See the doOp(Soldier, methodName) function in class TestPeople for an example.

Code Example:

Virtual Function Reference Table

Substitutability:

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 references of base type can be bound to an instance of any class that derives from the base. A function that accepts the base 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 Reference Table (VFRT).

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

Here, member function mf1 is not overridden by the derived class, so r2B.mf1() invokes the base's function. Member function mf2 is overridden by the derived class, so r2B.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