C++ Polymorphism

Polymorphism is a core concept in object-oriented programming that allows objects of different classes to be treated as objects of a common base class. It enables a single interface to represent different underlying forms (data types).

Key Topics

1. Compile-Time Polymorphism

Compile-time polymorphism is achieved through function overloading and operator overloading. The decision about which function or operator to invoke is made at compile time.

Example: Function Overloading

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

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

Code Explanation: The add function is overloaded to handle both integer and double types. The appropriate function is called based on the argument types.

2. Run-Time Polymorphism

Run-time polymorphism is achieved through inheritance and virtual functions. The decision about which function to invoke is made at runtime based on the object type.

Example: Virtual Functions

class Shape {
public:
    virtual void draw() {
        std::cout << "Drawing a shape";
    }
};

class Circle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a circle";
    }
};

class Square : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a square";
    }
};

Code Explanation: The draw function in the Shape class is declared as virtual, allowing derived classes Circle and Square to provide their own implementations. The correct draw method is called based on the object type at runtime.

3. Function Overloading

Function overloading allows multiple functions to have the same name with different parameters. It is a form of compile-time polymorphism.

4. Operator Overloading

Operator overloading allows you to define custom behavior for operators (like +, -, etc.) when they are used with user-defined types (classes).

Example: Operator Overloading

class Complex {
public:
    double real, imag;
    Complex(double r, double i) : real(r), imag(i) {}
    Complex operator + (const Complex& c) {
        return Complex(real + c.real, imag        + c.imag);
    }
};

Code Explanation: The operator + function is overloaded to allow the addition of two Complex objects. This enables the use of the + operator with instances of the Complex class.

Key Takeaways

  • Polymorphism allows objects of different classes to be treated as objects of a common base class.
  • Compile-time polymorphism is achieved through function and operator overloading.
  • Run-time polymorphism is achieved through inheritance and virtual functions, allowing method overriding.
  • Function overloading enables multiple functions with the same name but different parameters.
  • Operator overloading allows custom behavior for operators when used with user-defined types.