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:
-
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 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 methods and operators of a base class are inherited by classes derived from the base.
Note that inherited constructors and destructor are used to initialize and destroy the
derived class's internal base instance, via constructors and destructor that the
derived class defines, either explicitly or by the compiler.
- 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:
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: