Polymorph Is M 2012
Polymorph Is M 2012
Polymorphism
class D: public B { public void m(); Class D redefines method m() void p(); ... } // class D
CS-2303, C-Term 2010 Polymorphism 3
Review Accessing Members of Base and Derived Classes (continued) Access to members of a class object is determined by the type of the handle. Definition: Handle
Deitel & Deitel, 20.3
The thing by which the members of an object are accessed Note: this is not exactly the same May be
An object name (i.e., variable, etc.) by Stroustrup A reference to an object A pointer to an object
CS-2303, C-Term 2010 Polymorphism
Review Accessing Members of Base and Derived Classes (continued) This is referred to as static binding I.e., the binding between handles and members is determined at compile time
I.e., statically
Polymorphism
class Rectangle: public Shape { public: void Rotate(); void Draw(); ... } class Ellipse: public Shape { public: void Rotate(); void Draw(); ... }
Polymorphism
This tells the compiler to add internal pointers to every object of class Shape and its derived classes, so that pointers to correct methods can be stored with each object.
C++ dynamically chooses the correct method for the class from which the object was instantiated.
Polymorphism
Notes on virtual
If a method is declared virtual in a class,
it is automatically virtual in all derived classes
class Shape { public: virtual void Rotate(); virtual void Draw(); ... } class Line: public Shape { public: void Rotate(); //Use base class Draw method ... }
CS-2303, C-Term 2010 Polymorphism 10
Example
Deitel & Deitel, 24.3
CommissionEmployee and BasePlusCommissionEmployee
Polymorphism
11
Polymorphism
The ability to declare functions/methods as virtual is one of the central elements of polymorphism in C++
Dynamic binding with virtual functions only occurs from pointer and reference handles
CS-2303, C-Term 2010
Have not been able to verify Polymorphism from any other source!
13
Questions?
Polymorphism
15
Definitions
Normally used as base classes and called abstract base classes
Provide appropriate base class frameworks from which other classes can inherit.
Concrete Classes
Classes used to instantiate objects Must provide implementation for every member function they define
CS-2303, C-Term 2010 Polymorphism 16
Example
virtual void draw() const = 0;
If even one pure virtual function is not overridden, the derived-class will also be abstract
Compiler will refuse to create any objects of the class Cannot call a constructor
CS-2303, C-Term 2010 Polymorphism 18
Purpose
When it does not make sense for base class to have an implementation of a function Software design requires all concrete derived classes to implement the function
Themselves
Polymorphism
19
Questions?
Polymorphism
23