What is Polymorphism in C++: Explanation and Example
polymorphism allows objects of different classes to be treated through a common interface, typically using base class pointers or references. It enables calling the correct function for an object at runtime, even if the exact type is not known at compile time.How It Works
Polymorphism in C++ works by letting a program decide which function to call at runtime based on the actual object type, not just the pointer or reference type. Imagine you have a remote control that can operate different devices like a TV or a music player. You press the same button, but the device reacts differently depending on what it is. This is similar to polymorphism where the same function call behaves differently for different objects.
This is usually done using virtual functions in a base class. When a function is marked as virtual, C++ keeps track of the actual object type and calls the right function version when you use a base class pointer or reference. This mechanism is called dynamic dispatch.
Example
This example shows a base class Animal with a virtual function makeSound(). Two derived classes Dog and Cat override this function. When calling makeSound() through a base class pointer, the correct version runs depending on the actual object.
#include <iostream> using namespace std; class Animal { public: virtual void makeSound() { cout << "Some generic animal sound" << endl; } virtual ~Animal() {} }; class Dog : public Animal { public: void makeSound() override { cout << "Woof!" << endl; } }; class Cat : public Animal { public: void makeSound() override { cout << "Meow!" << endl; } }; int main() { Animal* animal1 = new Dog(); Animal* animal2 = new Cat(); animal1->makeSound(); // Calls Dog's makeSound animal2->makeSound(); // Calls Cat's makeSound delete animal1; delete animal2; return 0; }
When to Use
Use polymorphism when you want to write flexible and reusable code that works with different types of objects through a common interface. It is especially useful in large programs where you want to add new types without changing existing code.
For example, in a graphics program, you might have a base class Shape and derived classes like Circle, Rectangle, and Triangle. You can store pointers to different shapes in a list and call a draw() function on each without knowing the exact shape type. Polymorphism ensures the right draw() function runs for each shape.
Key Points
- Polymorphism allows one interface to control access to different underlying forms (data types).
- It is implemented in C++ using
virtual functionsand base class pointers or references. - Enables dynamic method dispatch, deciding at runtime which function to call.
- Helps write extensible and maintainable code by separating interface from implementation.