Lesson 18 — Object-Oriented Programming

Polymorphism

Polymorphism lets objects of different derived classes be treated through a common base class interface, with each object responding to the same call in its own way.

Virtual Functions

By default, C++ resolves which function to call at compile time based on the declared type of a pointer or reference. Marking a base class method virtual tells the compiler to instead resolve it at runtime, based on the object's actual type — this is what enables true polymorphism.

C++ — Virtual functions
class Shape {
public:
    virtual double area() { return 0; }
    virtual ~Shape() {} // virtual destructor is important here
};

class Circle : public Shape {
public:
    double radius;
    Circle(double r) : radius(r) {}
    double area() override { return 3.14159 * radius * radius; }
};

class Square : public Shape {
public:
    double side;
    Square(double s) : side(s) {}
    double area() override { return side * side; }
};

int main() {
    Shape* shapes[] = { new Circle(5), new Square(4) };
    for (Shape* s : shapes) {
        std::cout << "Area: " << s->area() << std::endl; // calls the correct override
    }
    return 0;
}

Common Mistakes

  • Forgetting the virtual keyword on the base class method, which silently disables polymorphism and calls the base version instead.
  • Omitting a virtual destructor in a base class that will be deleted through a base class pointer, which can cause resource leaks.
  • Forgetting override on a derived method — while not strictly required, it lets the compiler catch typos in the function signature.
  • Assuming polymorphism works with objects stored by value rather than through pointers or references — value storage causes "object slicing".

Professional Tip

Always add override to functions in derived classes that are meant to replace a virtual base function. If the signature doesn't actually match the base class (a common typo), the compiler will raise an error instead of silently creating an unrelated new function.

Your Turn

Add a Triangle class that inherits from Shape in the example above, implementing its own area() using base and height. Add it to the shapes array and confirm the correct area is printed for all three shapes.

Mini Quiz

What keyword must a base class method have for derived classes to override it polymorphically?