Before beginning this I would like to tell you one thing through the following program:
// Virtual Functions and
// Run-time Polymorphism
#include <iostream.h>
// base class
class base
{
public:
int a;
};
// derived class
class derived:public base
{
public:
int b;
};
// main
void main()
{
base b;
derived d;
// base class pointer
base *bptr;
// pointer pointing
// to base's object
bptr=&b;
bptr->a=10;
// pointer pointing
// to derived's object
bptr=&d;
// still is able to access
// the members of the base
// class
bptr->a=100;
}
The property above combined with virtual function can be used to achieve a very special and powerful feature, known as run-time polymorphism.
We had discussed about What is Polymorphism before so we wont be discussing it here.
The program below illustrates how virtual functions can be used to achieve run-time polymorphism.
Please read the code carefully so that you understand how it’s working.
// Using Virtual functions to
// achieve run-time Polymorphism
#include <iostream.h>
// base class
class base
{
public:
virtual void func()
{
cout<<"Base's func()\n";
}
};
// derived class
class derived:public base
{
public:
void func()
{
cout<<"Derived's func()\n";
}
};
// main
void main()
{
int ch=0;
base b;
derived d;
// base class pointer
base *bptr;
while(ch!=3)
{
cout<<"1> Call Base's func\n";
cout<<"2> Call Derived's func\n";
cout<<"3> Quit\n";
cin>>ch;
switch(ch)
{
case 1:
// point to base's object
bptr=&b;
break;
case 2:
// point tp derived's object
bptr=&d;
break;
default:
bptr=&b;
}
// call whichever function
// user has chosen to call
bptr->func();
}
}
Related Articles: