Polymorphism

Polymorphism

Polymorphism

Polymorphism in C++ is the ability of objects of different classes to be treated as if they were objects of a common base class. There are two types of polymorphism in C++:

  1. Compile-time Polymorphism (Static Polymorphism): This  is achieved through function overloading and operator overloading, where the compiler resolves the function call or operator used based on the arguments passed and their types at compile-time.

Here’s an example of function overloading:

				
					#include <iostream>
using namespace std;

class Calculator {
public:
    int add(int a, int b) {
        return a + b;
    }
    float add(float a, float b) {
        return a + b;
    }
};
int main() {
    Calculator calc;
    cout << calc.add(2, 3) << endl;       // calls int add(int, int)
    cout << calc.add(2.5f, 3.5f) << endl; // calls float add(float, float)
    return 0;
}

				
			
  1. Run-time Polymorphism (Dynamic Polymorphism): This  is achieved through inheritance and virtual functions. In this case, the function call is resolved at runtime based on the actual object type pointed to by the pointer or reference variable.

Here’s an example of runtime polymorphism using virtual functions:

				
					#include <iostream>
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* s1 = new Circle();
    Shape* s2 = new Rectangle();
    s1->draw(); // calls Circle's draw()
    s2->draw(); // calls Rectangle's draw()
    return 0;
}

				
			

Note that the virtual keyword is used in the base class method declaration to indicate that the method is virtual, and it is overridden in the derived classes using the override keyword.

Join To Get Our Newsletter
Spread the love