Virtual Function in C++
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
#include<iostream>
using namespace std;
class Base // abstract class
{
public:
virtual void display()=0; //pure virtual function
};
class Derived1:public Base
{
public:
void display()
{
cout<<"Display of Derived 1 \n ";
}
};
class Derived2:public Base
{
public:
void display()
{
cout<<"Display of Derived 2 \n ";
}
};
int main()
{
system("cls");
Base *p;
Derived1 D1;
Derived2 D2;
p=&D2;
p->display();
return 0;
}
// class Base
// {
// int n=0;
// public:
// Base()
// {
// cout<<"I am constructor"<<endl;
// }
// void increment()
// {
// ++n;
// }
// void display()
// {
// cout<<n;
// }
// };
// int main()
// {
// system("cls");
// Base B1; // actual object
// Base *B2; // reference object
// B2=&B1;
// B1.increment();
// B1.increment();
// B1.increment();
// B1.increment();
// B2->increment();
// B1.display();
// return 0;
// }Program 2
#include<iostream>
using namespace std;
class Button
{
public:
virtual void click()=0;
};
class MyImage:public Button
{
public:
void click()
{
cout<<" Hello This my image";
}
};
class MyColor:public Button
{
public:
void click()
{
cout<<" Hello Now color is red";
}
};
int main()
{
system("cls");
Button *p;
MyImage M1;
MyColor M2;
p=&M1;
p->click();
return 0;
} Did we exceed your expectations?
If Yes, share your valuable feedback on Google

