Abstract Class
P. Vasuki
Polymorphism
• On overriding, compiler calls the appropriate function,
defined by the type of object, which invokes the function.
Employee e, *ePtr = &e;
part_time_emp h, *hPtr = &h;
ePtr->print(); //call base-class print function
hPtr->print(); //call derived-class print function
ePtr=&h; //allowable implicit conversion
ePtr->print(); // still calls base-class print
If we want to call part_time employee print we should make
print of base class employee to be declared as virtual
Employee e, *ePtr = &e;
HourlyWorker h, *hPtr = &h;
ePtr->print(); //call base-class print function
hPtr->print(); //call derived-class print function
ePtr=&h; //allowable implicit conversion
ePtr->print(); // calls derived-class print
Dynamic Binding
• Dynamic binding (late binding )
– Object's type not needed when compiling virtual
functions
– Accommodate new classes that have been added
after compilation
Abstract Classes
• If a class Which consists of atleast one
pure virtual function is called as virtual
class or abstract class.
Pure virtual function
virtual double earnings() const = 0;
Case Study: Dynamic binding and
Implementation
Dzire_Car
virtual int milage()=0 //Pure Vitual Function
Pertrol__Dezire Deisel_Dezire
int milage() int milage()
{ {
return 22; I return 25;
} }
Virtual Destructors
• Problem:
– If base-class pointer to a derived object is deleted, the base-class
destructor will act on the object
• Solution:
– Declare a virtual base-class destructor
– Now, the appropriate destructor will be called
Polymorphism, virtual Functions and
Dynamic Binding
• When to use polymorphism
– Polymorphism has a lot of overhead
– Polymorphism is not used in STL (Standard Template
Library) to optimize performance
• virtual function table (vtable)
– Every class with a virtual function has a vtable
– For every virtual function, vtable has a pointer to the
proper function
• If a derived class has the same function as a base class,
then the function pointer points to the base-class function
– Detailed explanation in Fig. 20.2