Polymorphism
poly morphism
Compile-time/early binding/static binding
Runtime /late binding /dynamic binding
Runtime polymorphism
being able to assign different meaning to the same function at
runtime
allow us to program more abstractly
Think general vs Specific
Let C++ figure out which function to call at Run-time
Not the default in C++,runtime polymorphism can be achieved via
inheritance
base class pointer or references
virtual functions
Account a
a. withdraw() //Account : : withdraw
Account
Savings b
Withdraw()
b. withdraw() //Saving : : withdraw
Checking c
Savings Checking
c. withdraw() //Checking : : withdraw
Withdraw() Withdraw()
Trust d
d. withdraw() //Trust : : withdraw Trust
Withdraw()
Account * p =new Trust()
P->withdraw(1000); //Account : : withdraw
What should have been called was //Trust : : withdraw
void display_accout(const Account &acc)
{
acc.display(); Account
//will always use Accout::display display()
}
Account a; Savings Checking
display_account(a);
display() display()
Savings b;
display_account(b);
Trust
Checking c; display()
display_account(c);
Trust d;
display_account(d);
Virtual Function
Define a method as virtual, and the subclass
method overrides the base class method
E.g.,
class Shape {
public:
virtual void Rotate();
virtual void Draw();
...
}
Virtual Functions
If a method is declared virtual in a class,
… it is automatically virtual in all derived
classes
It is a really, really good idea to make
destructors virtual!
virtual ~Shape();
Reason: to invoke the correct destructor,
no matter how object is accessed
Abstract Classes
Classes from which it is never intended to instantiate
any objects
Incomplete—derived classes must define the “missing
pieces”.
Too generic to define real objects.
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
Pure virtual functions
A class is made abstract by declaring one or
more of its virtual functions to be “pure”
I.e., by placing "= 0" in its declaration
Example
virtual void draw() const = 0;
"= 0" is known as a pure specifier.
Tells compiler that there is no implementation