Page 232 - DCAP404 _Object Oriented Programming
P. 232
Unit 10: Virtual Functions and Polymorphism
chooses the member function that matches the type of the pointer. Thus, the polymorphism Notes
stated above cannot be implemented by this mechanism.
Polymorphism in C++
Compile time Runtime
polymorphism polymorphism
Function Operator Virtual
overloading overloading Function
Did u know? What is the disadvantage of polymorphism?
The biggest disadvantage of polymorphism is creation of reusable codes by programmers.
Classes once written, tested and implemented can be easily reused without caring about
what’s written in the cases.
C++ implements the runtime object polymorphism using a function type known as virtual
function. When a function with the same name is used both in the base class and the derived
class, the function in the base class is declared virtual by attaching the keyword virtual in the
base class preceding its normal declaration. Then C++ determines which function to use at run
time based on the type of object pointed to by the base pointer rather than the type of the
pointer. Thus, by making the base pointer to point to different objects, one can execute different
definitions of the virtual function as given in the program below.
#include <iostream.h>
class base
{
public:
void display()
{
cout<<“\n print base”;
}
virtual void show() //virtual function
{
cout<<“\n show base”;
}
};
class derived : public base
{
LOVELY PROFESSIONAL UNIVERSITY 225