A virtual function is a member function in a base class which get overridden by the member function of the derived class when a pointer of base class points to the object of the derived class. A virtual function starts with the keyword virtual.
When the pointer of a base class points to the object of the derived class, then member function of the base class is executed by default. The following program is without a virtual function. Here, member function print() of the base class ‘fruits‘ is executed when the program is run.
#include<iostream>
using namespace std;
class fruits {
public:
void print() {
cout<<"Fruits are tasty "<<endl;
}
};
class drinks : public fruits {
public:
void print() {
cout<<" Drinks are awesome "<<endl;
}
};
int main () {
drinks drinks1;
fruits* fruits1 = &drinks1;
fruits1 -> print();
return 0;
}
Output:
Fruits are tasty
When the member function is made virtual in the base class, member function of the derived class is executed when the program is run. In the following program member function of the base class ‘fruits‘ is made virtual. So, in the run time it will get overridden by member function print() of the derived class ‘drinks‘. Member function of the derived class will get executed.
#include<iostream>
using namespace std;
class fruits {
public:
virtual void print() {
cout<<"Fruits are tasty "<<endl;
}
};
class drinks : public fruits {
public:
void print() {
cout<<" Drinks are awesome "<<endl;
}
};
int main () {
drinks drinks1;
fruits* fruits1 = &drinks1;
fruits1 -> print();
return 0;
}
Output:
Drinks are awesome
A pure virtual function is a function which are used by the derived class but has no use in the base class. It is declared by assigning ‘0’. A class which has a pure virtual function is called an abstract class.
For an abstract class object is not created. Data members and members function except pure virtual function can be used in their derived classes.
The following program shows a pure virtual function print().
#include<iostream>
using namespace std;
class fruits {
public:
virtual void print() = 0;
};
class drinks : public fruits {
public:
void print() {
cout<<" Drinks are awesome "<<endl;
}
};
int main () {
drinks drinks1;
fruits* fruits1 = &drinks1;
fruits1 -> print();
return 0;
}