Object Oriented Programming
Object Oriented Programming
07: Polymorphism
1. Understanding Polymorphism
2. Dynamic Polymorphism
3. Virtual Functions
4. Virtual Destructors
5. Pure Virtual Functions
Dr. Imran Ihsan
Ph.D. in Knowledge Engineering
Associate Professor
Object Oriented Programming
2
07-01
Understanding Polymorphism
07: Polymorphism
Object Oriented Programming 07: Polymorphism
3
Polymorphism
Combination of two Greek words
Poly (many) morphism (form)
Water ➔ Solid, Liquid, Gas
In Shopping Mall Customer
In Metro Bus Passenger Same person have different
A Person behavior in different situations.
behaves
In University Student This is called Polymorphism.
In Home Daughter / Son
Object Oriented Programming 07: Polymorphism
4
Polymorphism
Polymorphism
Static Polymorphism / Dynamic Polymorphism /
Static Binding Dynamic Binding
Compile Time Run Time
Function Operator Virtual
Overloading Overloading Functions
Object Oriented Programming 07: Polymorphism
5
Binding Process
Binding is the process to associate variable/ function names with memory addresses
Binding is done for each variable and functions.
For functions, it means that matching the call with the right function definition by the compiler.
Compile-time Binding (Static Binding) Run-time Binding (Dynamic Binding)
Compile-time binding is to associate a function's Run-time binding is to associate a function's
name with the entry point (start memory name with the entry point (start memory
address) of the function at compile time (also address) of the function at run time (also called
called early binding) late binding)
C++ provides both compile-time and run-time bindings:
Non-Virtual functions (you have implemented so far) are binded at compile time
Virtual functions (in C++) are bound at run-time.
Why virtual functions are used? To implement Polymorphism
Object Oriented Programming 07: Polymorphism
6
Static Polymorphism
//Function Overloading
class SomeClass
{
public:
// function with 1 int parameter
void func(int x) int main() {
{
cout << "value of x is " << x << endl; SomeClass obj1;
} // The first 'func' is called
// function with same name but 1 double parameter obj1.func(7);
void func(double x)
{ // The second 'func' is called
cout << "value of x is " << x << endl; obj1.func(9.132);
}
// function with same name and 2 int parameters // The third 'func' is called
void func(int x, int y) obj1.func(85,64);
{ return 0;
cout << "value of x and y is " << x << ", " << y << endl; }
}
};
Object Oriented Programming 07: Polymorphism
7
Dynamic Polymorphism
There is an inheritance hierarchy
There is a pointer/reference of base class type that can point/refer to derived class objects
Object Oriented Programming 07: Polymorphism
8
Pointers to Derived Classes
C++ allows base class pointers or references to point/refer to both base class objects and all derived
class objects.
Let’s assume: While it is allowed for a base class pointer to
class Base { … }; point to a derived object, the reverse is not true.
class Derived : public Base { … }; Base b1;
Derived *pd = &b1; // compiler error
Then, we can write:
Base *p1;
Derived d_obj; p1 = &d_obj;
Base *p2 = new Derived;
Object Oriented Programming 07: Polymorphism
9
Pointers to Derived Classes
Access to members of a class object is determined by the type of
An object name (i.e., variable, etc.)
A reference to an object
A pointer to an object
Using a base class pointer (pointing to a derived class object) can access
only those members of the derived object that were inherited from the base.
This is because the base pointer has knowledge only of the base class.
It knows nothing about the members added by the derived class.
Object Oriented Programming 07: Polymorphism
10
Pointer / Reference of Base Class
OUTPUT OUTPUT
A’s Func A’s Func
Pointer of Base Class Reference of Base Class
Object Oriented Programming 07: Polymorphism
11
Pointer of Base Class
Parent class pointer/reference
has NO KNOWLEDGE of child
class functions
Object Oriented Programming 07: Polymorphism
12
Based and Derived Class Pointers
Base-class pointer pointing to base-class object
Straightforward
Derived-class pointer pointing to derived-class object
Straightforward
Base-class pointer pointing to derived-class object
Safe
Can access non-virtual methods of only base-class
Can access virtual methods of derived class
Derived-class pointer pointing to base-class object
Compilation error
Object Oriented Programming
13
07-02
Dynamic Polymorphism
07: Polymorphism
Object Oriented Programming 07: Polymorphism
14
Dynamic Polymorphism
There is an inheritance hierarchy
There is a pointer/reference of base class type that can point/refer to derived class objects
There is a pointer of base class type that is used to invoke virtual functions of derived class.
The first class that defines a virtual function is the base class of the hierarchy that uses dynamic
binding for that function name and signature.
Each of the derived classes in the hierarchy must have a virtual function with same name and
signature.
Not an error but needed for dynamic binding
Object Oriented Programming 07: Polymorphism
15
Virtual Functions
Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class
The resolving of function call is done at runtime
The virtual-ness of an operation is always inherited
If a function is virtual in the base class, it must be virtual in the derived class
Even if the keyword “virtual” not specified (But always use the keyword in children's classes for clarity.)
If no overridden function is provided, the virtual function of base class is used
Object Oriented Programming 07: Polymorphism
16
Virtual Functions
Declaring a function virtual will ensure late-binding
To declare a function virtual, we use the Keyword virtual:
class Shape {
public:
virtual void sayHi ( ) {
cout <<“Just hi! \n”;
}
};
Object Oriented Programming 07: Polymorphism
17
Virtual Functions
OUTPUT
B’s Func
Object Oriented Programming 07: Polymorphism
18
Virtual Functions
Overridden function parameters
in derived class must be same
OUTPUT as base class, otherwise base
A’s Func class func will be called
Object Oriented Programming 07: Polymorphism
19
Virtual Functions
Override Keyword
OUTPUT
B’s Func
Object Oriented Programming 07: Polymorphism
20
Virtual function with Multilevel Inheritance
OUTPUT
C’s Func
Object Oriented Programming 07: Polymorphism
21
Virtual function with Multilevel Inheritance
Class C does not override
func( ), if parent of class C has
OUTPUT
func( ), that one is executed
B’s Func
Object Oriented Programming 07: Polymorphism
22
Virtual function with Multilevel Inheritance
Class C does not override
func( ), Class B does not
OUTPUT override func( ), A’s func is
A’s Func executed
Object Oriented Programming
23
07-03
Virtual Functions
07: Polymorphism
Object Oriented Programming 07: Polymorphism
24
Virtual Functions
If the member function definition is out-of-line, the keyword virtual must not be specified again.
Virtual functions can not be stand-alone or static functions
A destructor can be virtual, but a constructor cannot
Object Oriented Programming 07: Polymorphism
25
Virtual Functions based Shapes
class Shape { int main( ) {
public: Shape *p;
virtual void sayHi( ) { cout<<“Just Hi!”; } int which;
}; cout<<“1 -- Shape, 2 -- Triangle, 3 -- Rectangle”<<endl;
class Triangle : public Shape { cin>>which;
public: switch (which) {
case 1: p = new Shape; break;
virtual void sayHi( ) { cout<<“Hi from Triangle!”; }
case 2: p = new Triangle; break;
};
case 3: p = new Rectangle; break;
class Rectangle : public Shape {
}
public:
p -> sayHi( ); //dynamic binding of sayHi( )
virtual void sayHi( ) { cout<<“Hi from Rectangle!”; }
delete p;
};
}
Object Oriented Programming 07: Polymorphism
26
Virtual Functions
class Animal { int main( ) {
public: Animal *pA = { new Animal, new Dog, new Cat };
virtual void id( ) { cout<<“Animal”; } for ( int i = 0; i < 3; i++ ) {
}; pA[ i ] -> id( ); //will print animal, dog, cat
class Cat : public Animal { }
public:
If the member functions id( ) are declared virtual,
virtual void id( ) { cout<<“Cat”; }
then the code will print animal, dog, cat.
};
class Dog : public Animal {
public:
virtual void id( ) { cout<<“Dog”; }
};
Object Oriented Programming 07: Polymorphism
27
Virtual Functions With Multiple Inheritance
class A { class C : public B, public A {
public: public:
void print( ) { cout<<“Print Class A”; } //not virtual void print( ) { cout<<“Print Class C”; }
~C( ) { cout<<“C’s Destructor” << endl; }
~A( ) { cout<<“A’s Destructor” << endl; }
};
};
class B {
int main( ) {
public:
B *b = new C;
virtual void print( ) { cout<<“Print Class B”; }
A *a = new C;
~B( ) { cout<<“B’s Destructor” << endl; } OUTPUT
b -> print ( );
}; Print Class C
a -> print ( ); Print Class A
return 0;
}
Object Oriented Programming 07: Polymorphism
28
Benefits of Polymorphism
Better Design!
Flexibility
You can always change the subclass object assigned to the superclass reference variable,
without breaking other code
The modification will only affect the new object, not those using it
Need to Write Less code
Reference variable of superclass type can be assigned object of any subclass
Easy to Extend
Write code that doesn’t have to change when you introduce new subclass types into the program.
Object Oriented Programming 07: Polymorphism
29
Pointers to Derived Classes
We can create an array of base class pointers,
and these pointers can hold objects of different derived classes
Shape *p[ 4 ];
p[ 0 ] = new Triangle (3, 4, 5, 19 );
p[ 1 ] = new Circle (3, 4, 5 );
p[ 2 ] = new Rectangle ( 3, 4, 10 , 20 );
p[ 3 ] = new Cylinder ( 3, 4, 5, 10 );
for ( int loop = 0; loop < 4; loop ++ ) {
p[ loop ]->draw ( );
cout << “The area is “ << p[loop]->GetArea ( );
}
Object Oriented Programming 07: Polymorphism
30
Dynamic Polymorphism Example
class Shape { Void print( Shape obj, Shape *ptr, Shape &ref ) {
public: ptr -> sayHi( ); //bound at run time
virtual void sayHi( ) { cout<<“Just Hi!”; } ref . sayHi( ); //bound at run time
}; obj . sayHi( ); //bound at compile time
class Triangle : public Shape { }
public:
int main( ) {
virtual void sayHi( ) { cout<<“Hi from Triangle!”; }
Triangle myTri;
};
print( myTri, &myTri, myTri );
}
Object Oriented Programming
31
07-04
Virtual Destructors
07: Polymorphism
Object Oriented Programming 07: Polymorphism
32
Virtual Destructors
Constructors cannot be virtual, but destructors can be virtual
when a constructor of a class is executed, there is no virtual table in the memory,
means no virtual pointer defined yet.
Ensures the derived class destructor is called when a base class pointer is used,
while deleting a dynamically created derived class object.
virtual ~Shape( ){….}
Reason: to invoke the correct destructor, no matter how object is accessed
Object Oriented Programming 07: Polymorphism
33
Virtual Destructors - Using Non-Virtual Destructor
class Base { int main( ) {
public: Base *p = new Derived;
~Base( ) { cout<<“Destructing Base… ”; } delete p;
}; return 0;
class Derived : public Base { }
public:
~Derived( ) { cout<<“Destructing Derived… ”; }
};
OUTPUT
Destructing Base
Object Oriented Programming 07: Polymorphism
34
Virtual Destructors - Using Virtual Destructor
class Base { int main( ) {
public: Base *p = new Derived;
virtual ~Base( ) { cout<<“Destructing Base… ”; } delete p;
}; return 0;
class Derived : public Base { }
public:
~Derived( ) { cout<<“Destructing Derived… ”; }
};
OUTPUT
Destructing Derived
Destructing Base
Object Oriented Programming 07: Polymorphism
35
Virtual Destructors - Using Virtual Destructor
class A { int main( ) {
public: B *b = new B; A *a = new A;
void print( int b ) { cout<<“Print Class A”; } delete a; delete b;
~A( ) { cout<<“A’s Destructor” << endl; } OUTPUT
B bb; C c; A aa;
}; A’ Destructor
return 0;
class B : public A { B’ Destructor
} A’ Destructor
public:
A’ Destructor
virtual void print( int a=0) { cout<<“Print Class B”; }
For Dynamic Objects: C’ Destructor
~B( ) { cout<<“B’s Destructor” << endl; }
Destructors are called with delete only and B’ Destructor
}; A’ Destructor
in the order of delete statements
class C : public B { B’ Destructor
For Simple Objects (in the same scope):
public: A’ Destructor
Destructors are called in opposite order
~C( ) { cout<<“C’s Destructor” << endl; } i.e., the one declared last is destroyed first
}; Without delete
Destructor is not called for dynamic objects
Object Oriented Programming
36
07-05
Pure Virtual Functions
07: Polymorphism
Object Oriented Programming 07: Polymorphism
37
Types of Inheritance/ Class Access Specifier
Abstract Classes Concrete Classes
Classes that cannot be instantiated Classes that can be instantiated (have objects)
(a class with no objects), because:
It is Incomplete Must provide implementation for every member function
—derived classes must define the “missing pieces” they define
Too generic to define real objects
Normally used as base classes and called abstract base
classes
Abstract Fruit
Apple Mango Concrete
Object Oriented Programming 07: Polymorphism
38
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( ) = 0;
"= 0" is known as a pure specifier. Tells compiler that there is no implementation.
Every concrete derived class must override all base-class pure virtual functions
with concrete implementations
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
Object Oriented Programming 07: Polymorphism
39
Pure Virtual Functions
A class with even one
pure virtual function is an
abstract class
Object Oriented Programming 07: Polymorphism
40
Pure Virtual Functions
Object Oriented Programming 07: Polymorphism
41
Why Do we Want to do This?
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 their own function
To define a common public interface for the various classes in a class hierarchy
Achieve dynamic polymorphism
The heart of object-oriented programming
Simplifies a lot of big software systems
Enables code re-use in a major way
Readable, maintainable, adaptable code