Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base class. In C++, polymorphism enables you to write more flexible and extensible code.
C++ supports two main types of polymorphism:
This guide focuses on runtime polymorphism, which is the more powerful and flexible form.
Runtime polymorphism allows a program to decide which function to call at runtime, based on the actual type of the object. This is achieved through virtual functions and inheritance.
Virtual functions are member functions declared in a base class and overridden in derived classes. They are declared using the virtual
keyword.
class Shape {
public:
virtual double area() const {
return 0;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
};
In this example, area()
is a virtual function in the base class Shape
and is overridden in the derived class Circle
.
To utilize polymorphism, you typically use pointers or references to the base class:
Shape* shape = new Circle(5);
double area = shape->area(); // Calls Circle::area()
delete shape;
This code demonstrates how a base class pointer can be used to call the appropriate derived class function.
override
keyword when overriding virtual functions to catch errors at compile-time.Polymorphism is a powerful feature in C++ that enables more flexible and maintainable code. By mastering this concept, you can create more robust and extensible object-oriented designs. Remember to use it judiciously and consider the performance implications in your specific use case.
For more advanced topics related to polymorphism, explore abstract classes and interfaces (pure virtual functions) in C++.