C++ Polymorphism

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common base class. The term polymorphism comes from Greek, where "poly" means many and "morphs" means forms, implying "many forms." This capability is crucial for designing flexible and reusable software.

Definition: Polymorphism enables objects to be treated as instances of their parent class rather than their actual class. It allows a single function or operator to operate in multiple ways depending on the object it is acting upon.

Types of Polymorphism:

1. Compile-Time Polymorphism (Static Polymorphism): Achieved through function overloading and operator overloading. The function or operator is chosen at compile-time based on its parameters or operand types.

Example:

<#include <iostream>>

class Print {
  public:
    // Method to print an integer
    void show(int i) {
      std::cout << "Integer: " << i << std::endl;
    }

    // Method to print a double
    void show(double d) {
      std::cout << "Double: " << d << std::endl;
    }
};

int main() {
  Print p;
  p.show(5); // Calls show(int i)
  p.show(3.14); // Calls show(double d)

  return 0;
}

Output:

Integer: 5
Double: 3.14

2. Run-Time Polymorphism (Dynamic Polymorphism): Achieved through virtual functions and inheritance. The function to be executed is determined at runtime based on the type of the object pointed to or referenced.

Example:

<#include <iostream>>

class Base {
  public:
    // Virtual method to be overridden by derived classes
    virtual void display() {
      std::cout << "Display Base" << std::endl;
    }
};

class Derived : public Base {
  public:
    // Override the base class method
    void display() override {
      std::cout << "Display Derived" << std::endl;
    }
};

// Function that demonstrates polymorphism
void showDisplay(Base* obj) {
  obj->display(); // Calls the appropriate display method based on the actual object type
}

int main() {
  Base b; // Create an instance of Base
  Derived d; // Create an instance of Derived
  showDisplay(&b); // Calls Base::display()
  showDisplay(&d); // Calls Derived::display()

  return 0;
}

Output:

Display Base
Display Derived

Importance in OOP

Encapsulation: By providing a common interface, polymorphism allows for encapsulation where the implementation details can be hidden.

Inheritance: Polymorphism builds on inheritance, allowing derived classes to modify or extend the functionality of base classes.

Code Reusability: It supports code reuse and extends the functionality of existing code without modifying it.