Geek Slack

Learn C++
About Lesson


C++ Polymorphism


C++ Polymorphism

Polymorphism is a key principle in object-oriented programming (OOP) that allows objects to be treated as instances of their base class or as instances of their derived classes through a single interface. This enables flexibility and extensibility in designing and interacting with classes.

1. Example of Polymorphism

Example demonstrating runtime polymorphism (virtual functions):

#include <iostream>

// Base class declaration
class Shape {
public:
    // Virtual function
    virtual void draw() {
        std::cout << "Drawing Shape" << std::endl;
    }
};

// Derived class declaration overriding draw()
class Circle : public Shape {
public:
    // Override base class function
    void draw() override {
        std::cout << "Drawing Circle" << std::endl;
    }
};

// Derived class declaration overriding draw()
class Rectangle : public Shape {
public:
    // Override base class function
    void draw() override {
        std::cout << "Drawing Rectangle" << std::endl;
    }
};

int main() {
    // Create objects of different shapes
    Shape* shape1 = new Shape();
    Shape* circle1 = new Circle();
    Shape* rectangle1 = new Rectangle();

    // Call draw() method - polymorphic behavior
    shape1->draw(); // Calls base class draw()
    circle1->draw(); // Calls derived class (Circle) draw()
    rectangle1->draw(); // Calls derived class (Rectangle) draw()

    // Cleanup
    delete shape1;
    delete circle1;
    delete rectangle1;

    return 0;
}

2. Types of Polymorphism

C++ supports two types of polymorphism:

  • Compile-time Polymorphism: Achieved through function overloading and operator overloading.
  • Runtime Polymorphism: Achieved through virtual functions and function overriding.

Conclusion

Polymorphism in C++ allows flexibility and extensibility in object-oriented design by enabling objects to be treated as instances of their base class or derived classes. This chapter covered runtime polymorphism using virtual functions, demonstrating how different objects can exhibit different behaviors through a common interface. Understanding polymorphism is essential for designing modular, maintainable, and scalable C++ programs.

Join the conversation