Polymorphism in C++
Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. It enables methods to do different things based on the object it is acting upon, even if the method name and signature are the same.
With polymorphism, a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. How to achieve this?
- Declare a virtual member function in base class
- Customized implement of the virtual member function in every derived class
- Create a base class pointer for a derived class object
- Access the derived class member function through base class pointer.
Code Example
Explanation
Abstract Class and Pure Virtual Function
class Animal {
virtual void move() = 0; // declare pure virtual function for polymorphism
};
- The Animal class is an abstract class because it contains a pure virtual function move().
- The pure virtual function is declared with = 0 and must be overridden by any derived class.
Concrete Classes
class Horse : public Animal {
void move() {
cout << "Child chass: horse runs with legs" << endl; // implement for horse class
}
};
class Fish : public Animal {
void move() {
cout << "Child chass: fish swims in water" << endl; // implement for fish class
}
};
- Horse and Fish are concrete classes derived from Animal.
- They override the move() function, providing their specific implementations.
Non-virtual Function
class Animal {
void live() { // non-virtual function, not for polymorphism
cout << "Parent class: animal lives on earth" << endl;
}
};
- The live() function in Animal is a regular function (not virtual) and is inherited by derived classes. However, the derived classes can still provide their own implementation of the live() function.
- In this example, the live() function of the derived classes are not used.
main function
shared_ptr animal[2];
animal[0] = make_shared(); // animal pointer to horse object
animal[1] = make_shared(); // animal pointer to fish object
for (int i = 0; i < 2; ++i) {
animal[i]->move(); // polymorphism: child function executed
animal[i]->live(); // not polymorphism: parent function executed
}
- In the main() function, we create an array of shared_ptr
and assign objects of Horse and Fish to it. - When calling animal[i]->move(), the appropriate move() function of the derived class (Horse or Fish) is executed, demonstrating polymorphism.
- When calling animal[i]->live(), the live() function of the Animal class is executed, not demonstrating polymorphism because live() is not a virtual function.
Conclusion
Polymorphism allows for flexibility and the ability to program to interfaces rather than specific implementations. It enables a single interface to represent different underlying forms (data types).