Polymorphism is one of the fundamental concepts of Object-Oriented Programming (OOP) that allows objects to have different behaviors while sharing the same interface. In C++, polymorphism is achieved through two mechanisms: function overloading and virtual functions.
Function Overloading:
Function overloading is a mechanism in which multiple functions can have the same name but with different parameters. The compiler selects the appropriate function to call based on the number and types of arguments passed to it. This is also known as compile-time polymorphism or static polymorphism.
Here is an example of function overloading:
cCopy code#include <iostream>
using namespace std;
class Calculator {
public:
int add(int x, int y) {
return x + y;
}
double add(double x, double y) {
return x + y;
}
};
int main() {
Calculator c;
cout << c.add(1, 2) << endl; // calls int add(int x, int y)
cout << c.add(1.5, 2.5) << endl; // calls double add(double x, double y)
return 0;
}
In this example, the Calculator
class has two add()
functions, one for integers and one for doubles. The appropriate function is called based on the data types of the arguments.
Virtual Functions:
Virtual functions allow a derived class to override the implementation of a base class function. This allows the derived class to have its own implementation of the function while still being able to use the same interface as the base class. This is also known as run-time polymorphism or dynamic polymorphism.
Here is an example of virtual functions:
arduinoCopy code#include <iostream>
using namespace std;
class Shape {
public:
virtual double getArea() {
return 0;
}
};
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double getArea() {
return length * width;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double getArea() {
return 3.14 * radius * radius;
}
};
int main() {
Shape* s1 = new Rectangle(5, 10);
Shape* s2 = new Circle(5);
cout << "Rectangle area: " << s1->getArea() << endl; // calls Rectangle::getArea()
cout << "Circle area: " << s2->getArea() << endl; // calls Circle::getArea()
delete s1;
delete s2;
return 0;
}
In this example, the Shape
class has a virtual getArea()
function, which is overridden by the Rectangle
and Circle
classes. When the getArea()
function is called on a Shape
pointer that points to a Rectangle
or Circle
object, the appropriate implementation is called based on the actual type of the object.
Conclusion:
Polymorphism is a powerful feature of C++ that allows objects to exhibit different behaviors while sharing the same interface. Function overloading and virtual functions are the two mechanisms used to achieve polymorphism in C++. Understanding these concepts is essential for writing effective and maintainable object-oriented code.