Introduction

Greetings! In today's lesson, we'll explore the concept of polymorphism in C++'s Object-Oriented Programming (OOP). Understanding polymorphism empowers us to utilize a single interface to represent different types in various situations. Let's get started.

Polymorphism: A Powerful OOP Principle

Polymorphism, one of the core principles of OOP, allows an object to take on multiple forms. Imagine a button in software; its behavior changes based on its type (e.g., a submit button versus a radio button). This dynamic showcases the essence of polymorphism!

Seeing Polymorphism in Action

Let's observe polymorphism in action through a simple application involving shapes. In the base Shape class, we define a pure virtual area method and a virtual destructor. The area method is uniquely implemented in the derived classes Rectangle and Circle, while the virtual destructor ensures that the destructors of derived classes are called appropriately, preventing resource leaks.

#include <iostream>
using namespace std;

class Shape {
public:
    virtual ~Shape() {} // virtual destructor
    virtual double area() const = 0; // pure virtual function
};

class Rectangle : public Shape {
private:
    double length, width;
public:
    Rectangle(double l, double w) : length(l), width(w) {}
    
    double area() const override { // calculate rectangle area
        return length * width;
    }
};

class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}
    
    double area() const override { // calculate circle area
        return 3.14 * radius * radius;
    }
};

int main() {
    Rectangle rectangle(2, 3);
    cout << rectangle.area() << endl; // Outputs: 6

    Circle circle(5);
    cout << circle.area() << endl; // Outputs: 78.5

    return 0;
}

In this example, polymorphism is demonstrated as the area function takes multiple forms and behaves differently based on whether it's attached to a Rectangle or a Circle. The inclusion of a virtual destructor in the Shape class ensures that when a derived object is deleted through a base pointer, the correct destructor is invoked, reflecting proper resource management and preventing memory leaks.

Dynamic Polymorphism: Runtime Method Overriding
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal