Polymorphism in C++ allows objects of different types to be treated uniformly. It comes in two forms: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism.
Compile-time polymorphism is achieved through function overloading and operator overloading. Function overloading lets multiple functions with the same name behave differently based on their parameters.
Runtime polymorphism is implemented using inheritance and virtual functions. It allows derived class methods to override base class methods and enables the object to call the appropriate method at runtime.
Using polymorphism makes the code more flexible and scalable. You can define common interfaces in base classes, and the derived classes implement their specific behavior.
// Example of polymorphism in C++
#include
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a rectangle" << endl;
}
};
int main() {
Shape* shape1 = new Circle();
Shape* shape2 = new Rectangle();
shape1->draw(); // Drawing a circle
shape2->draw(); // Drawing a rectangle
delete shape1;
delete shape2;
return 0;
}