Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows you to write code that can work with objects of different types. Polymorphism means "many forms", and in C++, there are two types of polymorphism: compile-time polymorphism and runtime polymorphism.
Compile-time polymorphism is achieved through function overloading and operator overloading, which we have already discussed earlier. At compile-time, the compiler selects the appropriate function or operator based on the arguments passed to it.
Runtime polymorphism is achieved through inheritance and virtual functions. When a function is declared as virtual in a base class, it becomes a virtual function, and its behavior can be overridden by derived classes. At runtime, the appropriate version of the virtual function is called based on the actual type of the object.
Here's an example to illustrate runtime polymorphism:
c++#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() const = 0;
};
class Circle : public Shape {
public:
void draw() const override {
cout << "Drawing a circle" << endl;
}
};
class Square : public Shape {
public:
void draw() const override {
cout << "Drawing a square" << endl;
}
};
int main() {
Shape* shapes[2];
shapes[0] = new Circle();
shapes[1] = new Square();
for (int i = 0; i < 2; i++) {
shapes[i]->draw();
}
return 0;
}
In this example, we have defined a Shape class with a virtual function named draw()
, which is declared as a pure virtual function by appending = 0
to the function signature. This makes the Shape class an abstract class, which means that it cannot be instantiated directly.
We have also defined two derived classes, Circle and Square, which override the draw()
function.
In the main()
function, we create an array of Shape pointers and assign a Circle object and a Square object to the first and second elements of the array, respectively. We then call the draw()
function on each object through the Shape pointer. Since the draw()
function is declared as virtual in the Shape class and overridden in the derived classes, the appropriate version of the function is called based on the actual type of the object.
Polymorphism is a powerful feature in C++ that allows you to write code that is more flexible and reusable. By using polymorphism, you can write code that works with objects of different types, without having to know the actual type of the object at compile-time.
Comments
Post a Comment