C++ Multiple Inheritance
Implement two narrow interfaces and recognise why a deep inheritance hierarchy raises design costs.
How it works
C++ supports multiple inheritance, including implementing several independent interfaces. That can be useful when an object must provide two distinct capabilities. Shared implementation inheritance is more demanding: repeated bases, ambiguous names and virtual-base initialization can complicate object layout and invariants. A multilevel hierarchy should preserve substitutability at every level rather than merely accumulate methods. Prefer composition for reusable state and keep interface inheritance shallow unless there is a concrete need.
Run it locally
Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror inheritance-design.cpp -o lessonOn Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.
Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.
Example
#include <iostream>
#include <string_view>
struct Named { virtual std::string_view name() const = 0; virtual ~Named() = default; };
struct Sized { virtual int units() const = 0; virtual ~Sized() = default; };
class Parcel final : public Named, public Sized {
public:
std::string_view name() const override { return "Crate"; }
int units() const override { return 3; }
};
int main() {
Parcel parcel;
const Named& named = parcel;
const Sized& sized = parcel;
std::cout << named.name() << ": " << sized.units() << " units\n";
}
Expected result
Crate: 3 units
Both references borrow the same live Parcel without taking ownership. The interfaces carry no shared mutable data and have independent contracts. A private or protected inheritance declaration changes accessibility and conversion rules; it does not become a substitute for choosing the correct domain relationship. Avoid exposing a complicated hierarchy in a beginner public API.
Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.