Polymorphism

Polymorphism

Polymorphism in C++ is a core concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. The term “polymorphism” comes from Greek roots meaning “many shapes” or “many forms,” and it enables you to write more flexible and reusable code.

There are two main types of polymorphism in C++: compile-time (static) polymorphism and runtime (dynamic) polymorphism.

  1. Compile-time Polymorphism (Static Polymorphism):
    • Compile-time polymorphism is achieved using function overloading and operator overloading.
    • Function overloading allows you to define multiple functions with the same name but with different parameters or parameter types. The appropriate function is chosen at compile time based on the arguments provided.
    • Operator overloading allows you to redefine the behavior of operators for user-defined types.

Example of Compile-time polymorphism:

#include <iostream>

class Calculator {
public:
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }
};

int main() {
    Calculator calc;
    std::cout << calc.add(5, 3) << std::endl;       // Calls int add(int, int)
    std::cout << calc.add(4.5, 2.3) << std::endl;   // Calls double add(double, double)
    return 0;
}

Output:

8
6.8
  1. Runtime Polymorphism (Dynamic Polymorphism):
    • Runtime polymorphism is achieved using inheritance and virtual functions.
    • Virtual functions allow a function in a base class to be redefined in a derived class. The appropriate function to call is determined at runtime based on the type of the object.
    • To declare a function as virtual, you use the virtual keyword in the base class.

Example of runtime polymorphism:

#include <iostream>

class Animal {
public:
    virtual void sound() {
        std::cout << "Animal makes a sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Dog barks" << std::endl;
    }
};

class Cat : public Animal {
public:
    void sound() override {
        std::cout << "Cat meows" << std::endl;
    }
};

int main() {
    Animal *animal1 = new Dog();
    Animal *animal2 = new Cat();

    animal1->sound(); // Output: Dog barks
    animal2->sound(); // Output: Cat meows

    delete animal1;
    delete animal2;

    return 0;
}

Output:

Dog barks
Cat meows

    Leave a Reply

    Your email address will not be published.

    Need Help?