C++ Inheritance and Polymorphism
C++ inheritance lets a new class reuse and extend an existing one. Polymorphism lets you treat different derived objects through a common base type and still get the right behavior for each.
Basic Inheritance
#include <iostream>
#include <string>
class Animal {
protected:
std::string name;
public:
explicit Animal(std::string n) : name(std::move(n)) {}
void eat() const { std::cout << name << " is eating\n"; }
};
class Dog : public Animal {
public:
using Animal::Animal; // reuse the base constructor
void bark() const { std::cout << name << " says Woof\n"; }
};
int main() {
Dog d("Rex");
d.eat();
d.bark();
}Rex is eating Rex says Woof
Virtual Functions and Polymorphism in C++
Marking a base function virtual lets derived classes override it. Calls through a base reference or pointer then use the derived version. Always add override in derived classes, and give the base a virtual destructor.
#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual double area() const = 0; // pure virtual: abstract class
virtual ~Shape() = default;
};
class Circle : public Shape {
double r;
public:
explicit Circle(double r) : r(r) {}
double area() const override { return 3.14159 * r * r; }
};
class Rect : public Shape {
double w, h;
public:
Rect(double w, double h) : w(w), h(h) {}
double area() const override { return w * h; }
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(1.0));
shapes.push_back(std::make_unique<Rect>(2.0, 3.0));
for (const auto& s : shapes) std::cout << s->area() << '\n';
}3.14159 6
Key Terms
- Base class (parent) and derived class (child).
- public inheritance models an "is-a" relationship.
- virtual enables runtime dispatch; override asks the compiler to check you really override something.
- A pure virtual function (= 0) makes the class abstract, so it cannot be instantiated.
- final prevents further overriding or inheritance.
Prefer Composition When It Fits
Not every relationship is "is-a". If a Car has an Engine, make Engine a member rather than inheriting from it. Use inheritance mainly for polymorphic interfaces.
Frequently asked questions
What is a virtual function in C++?
A member function declared with virtual that derived classes can override. When called through a base pointer or reference, the most-derived version runs at runtime.
Why does a base class need a virtual destructor?
If you delete a derived object through a base pointer and the destructor is not virtual, the derived destructor never runs, which is undefined behavior and often leaks resources.
What is an abstract class in C++?
A class with at least one pure virtual function (= 0). It cannot be instantiated and serves as an interface for derived classes.