Virtual & Polymorphism in C++

From the C++ cheat sheet · Inheritance & Polymorphism · verified Jul 2026

Virtual & Polymorphism

Dynamic dispatch, abstract classes, and casts.

cpp
// Quick Reference
class Shape {
public:
    virtual double area() const = 0;   // pure virtual -> abstract
    virtual ~Shape() = default;        // virtual destructor
};
class Circle : public Shape {
    double area() const override { return 3.14159 * r * r; }
    double r;
};
💡 virtual enables runtime dispatch - the actual object type decides which method runs.
⚡ Always give a polymorphic base class a virtual destructor, or deleting via a base pointer leaks.
📌 A pure virtual (= 0) makes the class abstract - it cannot be instantiated directly.
🟢 override lets the compiler verify you are actually overriding a base virtual.
virtualpolymorphism

More C++ tasks

Back to the full C++ cheat sheet