C++ Polymorphism
Polymorphism in C++ refers to an object’s capacity to assume several forms. It gives the code flexibility and extensibility by enabling diverse objects to be handled as though they were of the same type. Function overloading and virtual functions are two methods used in C++ to implement polymorphism.
Function Overloading:
When two or more functions with the same name but different parameters are specified in a class, this method is known as function overloading. Based on the quantity and types of inputs supplied to them, the compiler makes a distinction between them.
Example:
class MyClass {
public:
void myFunction(int x) {
cout << "The integer value is: " << x << endl;
}
void myFunction(double x) {
cout << "The double value is: " << x << endl;
}
};
int main() {
MyClass obj;
obj.myFunction(5);
obj.myFunction(3.14);
return 0;
}
Output:
The integer value is: 5
The double value is: 3.14
Virtual Functions:
Virtual functions are used to achieve runtime polymorphism. A virtual function is a member function that is declared in a base class and defined in a derived class. It enables us to call the derived class’s implementation of the function instead of the base class’s implementation.
Example:
class Shape {
public:
virtual void draw() {
cout << "Drawing a Shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a Circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a Rectangle" << endl;
}
};
int main() {
Shape *s;
Circle c;
Rectangle r;
s = &c;
s->draw();
s = &r;
s->draw();
return 0;
}
Output:
Drawing a Circle
Drawing a Rectangle
In this illustration, the virtual function draw() belongs to the Shape class, while the Circle and Rectangle classes have their own versions of the draw() function. Created objects of the Circle and Rectangle classes are assigned to a Shape class pointer by the main function. The draw() function is invoked using the pointer, and depending on the type of object the pointer points to, the relevant implementation is called.