Page 233 - DCAP404 _Object Oriented Programming
P. 233
Object-oriented Programming
Notes public:
void display()
{
cout<<“\n display derived”;
}
void show()
{
cout<<“\n show derived”;
}
};
main()
{
base bb;
derived dd;
base *baseptr;
cout <<“\nbaseptr points to the base \n”;
baseptr = &bb;
baseptr -> display(); //calls base function display()
baseptr -> show(); //calls base function show()
cout <<“\n\nbaseptr points to the derived \n”;
baseptr = ⅆ
baseptr -> display(); //calls derived function display()
baseptr -> show(); //calls derived function show()
}
The output of this program would be:
Baseptr points to base
Display base
Show base
Baseptr points to derived
Display derived
Show derived
Here, we see that the same object pointer points to two different objects of different classes and
yet selects the right function to execute. This is implementation of function polymorphism.
Remember, however, that runtime polymorphism is achieved only when a virtual function is
accessed through a pointer to the base class. It is also interesting to note that since, all the C++
classes are derived from the Object class, a pointer to the Object class can point to any object of
any class in C++.
226 LOVELY PROFESSIONAL UNIVERSITY