Virtual functions, virtual , base class pointer , base class
Write a C++ program to implement the concept of Virtual functions.


Algorithm to solve the above problem:
1. Start the program.
2. Define a base class called base and define a function called display as virtual in it.
3. Derive a new class called derv1,derv2 using a base class called base and define a function ‘display’ in the respective classes.
4. Declare a base class pointer in main function and objects for derv1 and derv2 classes.
6. Assign derv1 and derv2 obj to base pointer
7. Now display function shows the derv1 and derv2 class’ function respectively.

Implementation of the above problem in C++:
#include<iostream>
using namespace std;
class base
{
public:
virtual void display() 
{
cout<<"Base class display function is called \n";
}
};
class derv1:public base
{
public:
void display() 
{
cout<<"Derived1's class display function is called \n";
}
};
class derv2:public base
{
public:
void display() 
{
cout<<"Derived2's class display function is called \n";
}
};
int main()
{

base *ptr, b;
ptr=&b;
ptr->display();
derv1 d1;
derv2 d2;
ptr=&d1;
ptr->display();
ptr=&d2;
ptr->display();
return 0;
}

The output of the above program is tested on www.jdoodle.com
Output:
Base class display function is called 
Derived1's class display function is called 
Derived2's class display function is called 


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: