C++ Inheritance & Polymorphism

Base classes, virtual functions and override.

✍️ 2 exercises in this lesson
  • class Dog : public Animal: Dog inherits from Animal.
  • Mark functions virtual in the base class so derived versions run through base pointers or references.
  • Use override in derived classes so the compiler checks you really override something.
  • A pure virtual function (= 0) makes the class abstract.
  • Give base classes a virtual destructor.

Key Takeaways: C++ Inheritance & Polymorphism

Mastering C++ Inheritance & Polymorphism helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ Inheritance & Polymorphism Code Example

C++
#include <iostream>
#include <memory>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
    virtual const char* name() const = 0;
};

class Circle : public Shape {
    double r;
public:
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
    const char* name() const override { return "Circle"; }
};

class Square : public Shape {
    double s;
public:
    explicit Square(double s) : s(s) {}
    double area() const override { return s * s; }
    const char* name() const override { return "Square"; }
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1));
    shapes.push_back(std::make_unique<Square>(3));
    for (const auto& s : shapes) std::cout << s->name() << ": " << s->area() << "\n";
    return 0;
}
Output
Circle: 3.14159
Square: 9
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ Inheritance & Polymorphism Practice Exercises

Check what you learned in “C++ Inheritance & Polymorphism”.

/ 2 solved
Fill in the blank

Let derived classes override this method through base pointers.

 double area() const = 0;
✓ Correct! Not quite. Try again.
Multiple choice

What does "= 0" after a virtual function make it?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services