Polymorphism in object-oriented programming (OOP) is the ability of a single function or method to operate on multiple types of data. One common use of polymorphism in C++ is through the use of virtual functions.
Here is an example:
class Shape {
public:
virtual double area() = 0;
};
class Rectangle: public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}
};
class Circle: public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double area() {
return 3.14159 * radius * radius;
}
};
void printArea(Shape& s) {
cout << “Area is: ” << s.area() << endl;
}
int main() {
Rectangle rectangle(4, 5);
Circle circle(3);
printArea(rectangle);
printArea(circle);
return 0;
}
In this example, the Shape class is an abstract class that defines a virtual function area(). The Rectangle and Circle classes inherit from Shape and provide their own implementation of the area() function.
The printArea() function takes a reference to a Shape object and calls the area() function. Because of polymorphism, the correct version of the area() function is called, based on the actual type of the object passed to the function (either a Rectangle or a Circle). This allows the printArea() function to work with both types of objects without knowing the specific type at compile-time.