Write a C++ program to implement runtime polymorphism through virtual function.
Algorithm:
Step 1: Start the program
Step 2: Declare a base class called base
Step 3: Declare a derived class of class base
Step 4: In the main function create object for base and derived class
Step 5: Assign base ptr to base class object
Step 6: Assign base ptr to derived class object
Step 7: Invoke the particular functions
Step 8: Stop the program
Program Code:
#include<iostream.h>
#include <conio.h>
class base
{
public:
void display()
{
cout<<"display base class\n";
}
virtual void show()
{
cout<<"Show Base\n";
}
};
class derived :public base
{
public: void display()
{
cout<<"display derived class\n";
}
void show()
{
cout<<" show derived\n";
}
};
int main()
{
base b;
derived d;
base *bptr;
clrscr();
cout<<"\n bptr points to base\n";
bptr=&b;
bptr->display();
bptr->show();
cout<<"\n\n bptr points to derived\n";
bptr=&d;
bptr->display();
bptr->show();
getch();
return 0;
}
Output:
bptr points to base
display base class
Show Base
display base class
show derived
Post A Comment:
0 comments: