OOP

Inheritance and Polymorphism

Extend classes with inheritance and use polymorphism with virtual functions.

Inheritance

Inheritance lets a derived class inherit attributes and methods from a base class. Use : syntax.

Virtual Functions

Declare a function virtual to enable runtime polymorphism. Derived classes override virtual functions to provide specific implementations.

Pure Virtual Functions (Abstract Classes)

A function declared with = 0 is a pure virtual function. Classes containing them are abstract and cannot be instantiated — only used as base classes.

Virtual Destructors

Always make destructors virtual in base classes to ensure proper cleanup of derived objects.

Example

cpp
#include <iostream>
#include <vector>
#include <memory>
using namespace std;

// Abstract base class
class Shape {
public:
    virtual double area() const = 0;     // pure virtual
    virtual double perimeter() const = 0; // pure virtual
    virtual void draw() const {
        cout << "Drawing shape with area: " << area() << endl;
    }
    virtual ~Shape() {}  // virtual destructor!
};

class Circle : public Shape {
    double radius;
public:
    Circle(double r) : radius(r) {}

    double area() const override {
        return 3.14159 * radius * radius;
    }
    double perimeter() const override {
        return 2 * 3.14159 * radius;
    }
    void draw() const override {
        cout << "Drawing circle with radius " << radius << endl;
    }
};

class Rectangle : public Shape {
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const override { return width * height; }
    double perimeter() const override { return 2 * (width + height); }
};

int main() {
    // Polymorphism via base class pointers
    vector<unique_ptr<Shape>> shapes;
    shapes.push_back(make_unique<Circle>(5.0));
    shapes.push_back(make_unique<Rectangle>(4.0, 6.0));

    for (const auto& shape : shapes) {
        shape->draw();
        cout << "Area: " << shape->area() << endl;
    }

    return 0;
}
Try it yourself — CPP