Implementing Polymorphism in C++

Implementing Polymorphism in C++

Polymorphism means one name different forms. Polymorphism occurs in program when we inherit  base class to derived class having similar function. When base class has same function name as in derived class than the program return the value in base class because of early binding or static binding. In early binding function in the base class is read by compiler and its returns the same value during execution.

#include <iostream>
using namespace std;
class Pizza{
public: 
int get_price(){
cout << "Pizza is 500 \n" ;
}
};
class Ham: public Pizza{
public: 
int get_price(){
cout << "Ham is 200 \n"; 
}
};
class Mushroom: public Pizza{
public: 
int get_price(){
cout << "Mushroom is 250 " << endl; 
}
};
class Cheese: public Pizza{
public:
int get_price(){
cout << "Cheese is 300" << endl;
}
};
int main(){
Pizza *pizza[3];
pizza[0] = new Ham;
pizza[1] = new Mushroom;
pizza[2] = new Cheese;
for(int i = 0;i < 3 ; i++) {
cout << pizza[i] -> get_price(); 
} 
return 0;
}

Output of this program is:

Pizza is 500
Pizza is 500
Pizza is 500

Surprised!  So, to solve this program “virtual” keyword is used in base class method. Using this keyword we signal the compiler we don’t want early binding in our program.

class Pizza{
public: 
virtual int get_price(){
cout << "Pizza is 500 \n" ;
}
};

Result after adding virtual:

Ham is 200 
Mushroom is 250
Cheese is 300

 

Leave a Reply

Your email address will not be published. Required fields are marked *