Write a C++ program to illustrate virtual function implementation.
Program Code:
Step 1: Create a class base with a method marked as virtual.
Step 2: Create a subclass of the base called derived and redefine the method defined in step 1.
Step 3: Create an object pointer of type base and Create it point to an object of type base first and call the methods you had marked as virtual using -> operator.
Step 4: repeat the same steps but by making the pointer point to an object of the derived type now.
Program Code:
#include<iostream.h>
class base
{
public:
void display()
{
cout<<"\nDisplay base";
}
virtual void show()
{
cout<<"\nShow base.";
}
};
class derived:public base
{
public:
void display()
{
cout<<"\nDisplay derived";
}
void show()
{
cout<<"\nShow Derived.";
}
};
int main()
{
base b;
derived d;
base *bptr;
bptr=&b;
cout<<"\nbptr points to base\n";
bptr->display();
bptr->show();
cout<<"\n\nbptr points to derived.";
bptr=&d;
bptr->display();
bptr->show();
return 0;
}
Sample Inputs and Outputs:
bptr points to base
Show base
Display base
bptr points to derived
Show derived
Display derived
Post A Comment:
0 comments: