Inheritance
Inheritance builds one class on top of another: the derived class starts with a complete copy of the base class's members. With public inheritance it is also substitutable for the base, which is what runtime polymorphism needs.
Detailed Explanation
Start with the problem. You have a Report class that gathers rows from a database, formats a header, and writes to a stream. Now you need a PDF variant: same gathering, different layout. Copying the class leaves you with two copies of the gathering logic that drift apart over time. Inheritance lets a new class declare that it is a Report, reuse everything the base already does, and replace only the part that differs.
A derived object physically contains a complete base object, called the base subobject, plus whatever the derived class adds. The declaration names the base and an access level, and that access level decides what the relationship actually means.
publicinheritance models is-a. The base's public interface stays public, and aReport&orReport*can refer to aPdfReport. That substitutability is the foundation of virtual dispatch, and it is the only form most code should use.privateinheritance models implemented in terms of. The base's members become private in the derived class, and outside code cannot convert a derived pointer to a base pointer. You get the base's implementation without claiming to be a base. A member object expresses the same idea with less coupling, so private inheritance is reserved for cases where you must override a base virtual function or want the empty base optimisation.protectedinheritance is the rare middle ground: the relationship is visible to the derived class and to classes derived from it, but not to outside callers.
Objects are built base first. The base constructor runs, then the derived class's own members in declaration order, then the derived constructor body. Destruction is the exact reverse. Two consequences follow: a base constructor cannot use derived state because the derived part does not exist yet, and a base destructor cannot touch it either because it is already gone.
The most common beginner bug is slicing. Both Report r = pdf; and void print(Report r) copy only the base subobject. Everything the derived class added is discarded, and the copy's dynamic type is Report, so virtual calls on it run the base versions. No warning fires. The same loss happens to every element you push into a std::vector<Report>. Store polymorphic objects behind std::unique_ptr<Report> and pass them as const Report&.
If a base is used polymorphically, its destructor must be virtual. Deleting a derived object through a Report* with a non-virtual destructor is undefined behavior: the compiler may do anything, and what it usually does is run only the base destructor, leaking the derived members.
Mark every override override, and mark a class or function final when further derivation or overriding makes no sense. Both keywords arrived in C++11; legacy code had neither, so a one-character signature mismatch produced a new non-overriding function that compiled cleanly and ran the wrong code.
Prefer composition. Inheritance is the tightest coupling the language offers — a derived class depends on the base's protected members, construction order, and invariants, and it inherits every future change to them. A member object exposes only what you choose to forward. Inherit publicly when callers genuinely need to substitute your type for the base; hold a member otherwise.
Code Examples
#include <iostream>
#include <memory>
#include <string>
class Report {
public:
explicit Report(std::string title) : title_(std::move(title)) {
std::cout << "Report ctor\n";
}
virtual ~Report() { std::cout << "Report dtor\n"; } // virtual: deleted via base pointer
virtual void render() const { std::cout << "text: " << title_ << '\n'; }
protected:
std::string title_;
};
class PdfReport final : public Report { // final: nothing may derive from this
public:
explicit PdfReport(std::string title) : Report(std::move(title)) {
std::cout << "PdfReport ctor\n";
}
void render() const override { std::cout << "pdf: " << title_ << '\n'; }
};
int main() {
std::unique_ptr<Report> r = std::make_unique<PdfReport>("Q3");
r->render(); // prints: pdf: Q3
}
// order: Report ctor, PdfReport ctor, "pdf: Q3", Report dtor#include <memory>
#include <vector>
void byValue(Report r) { r.render(); } // WRONG: copies the base part only
void byRef(const Report& r) { r.render(); } // right: no copy, dynamic type preserved
void demo() {
PdfReport pdf("Q3");
byValue(pdf); // prints: text: Q3 <- the PdfReport half was sliced away
byRef(pdf); // prints: pdf: Q3
std::vector<Report> sliced; // element type is Report
sliced.push_back(pdf); // stores a sliced base copy
std::vector<std::unique_ptr<Report>> ok; // stores polymorphic objects
ok.push_back(std::make_unique<PdfReport>("Q4"));
}Common Gotchas
Slicing is silent
assigning or passing a derived object by base value copies only the base subobject and downgrades the dynamic type. The code compiles, runs, and quietly calls the wrong virtual functions. Pass `const Base&` or store `std::unique_ptr<Base>`.
A polymorphic base needs a virtual destructor
`delete` through a `Base*` whose destructor is not virtual is undefined behavior. Give any class that anyone will derive from and delete polymorphically a `virtual ~Base() = default;`.
Declaring a function in the derived class hides every base overload of that name
if `Base` has `log(int)` and `log(const std::string&)` and the derived class declares only `log(int)`, calls with a string stop compiling. Bring the rest back with `using Base::log;`.
Public inheritance purely for code reuse is a design smell
it forces an is-a claim you may not want to honour, and callers can then substitute your type for the base. Use a private member or private inheritance instead.