Polymorph Is M
Polymorph Is M
2
Inheritance
• A base class pointer can point to an object of a
derived class
– Derived class object “is-a” base class object
– But can’t use pointer to call methods only defined in
the derived class.
• A derived class pointer CANNOT point to the
base class
– The base class doesn’t have any of the extensions
provided by the derived class
3
Calling virtual methods from
within other methods
• Suppose virtual drawMe( ) is added to
Shape and inherited by Rectangle without
being overridden.
7
Don’t Pass by Value
A function which has a base class parameter passed by
value should only be used with base class objects –
for two reasons
1. The function isn’t polymorphic. Polymorphism
only occurs with parameters passed by pointer or
reference
2. Even though a derived class object can be passed to
such a function (a D is-a B), none of the derived
class methods or data members can be used in that
function. This is a phenomenon called “member
slicing”.
8
Polymorphism and Destructors
• A problem – if an object (with a non-virtual
destructor) is explicitly destroyed by applying the
delete operator to a base class pointer, the base class
destructor is invoked.
Circle C;
Shape *sp = &C;
delete sp; // calls Shape’s destructor
// if the destructor is not
// virtual
• So what ??
9
Polymorphism and Destructors
• Solution -- Declare a virtual destructor for
any base class with at least one virtual
function.
• Then, when the derived class’s destructor is
invoked, the base class destructor will also
be invoked automatically
10
Designing A Base Class with
Inheritance and Polymorphism
in mind
For the base class
1. Identify the set of operations common to all
the children
2. Identify which operations are type-
independent (these become (pure) virtual to
be overridden in derived classes)
3. Identify the access level (public, private,
protected) of each operation
For a more complete discussion, see “Essential C++”, Stanley Lippman (section 5.4)
11