# Lecture 19: Use inheritance only when substitution is safe ## Move from one value type to a justified is-a relationship **Instructor:** [Dr. Debasish Pattanayak](https://drdebmath.github.io)
## Friend access is a narrow exception, not an interface ~~~cpp class Complex { double real, imaginary; public: Complex(double r, double i) : real(r), imaginary(i) {} friend std::ostream& operator<<(std::ostream&, const Complex&); }; ~~~ A friend is a non-member granted narrow access. Friendship is not inheritance or a security boundary.
## Public inheritance promises substitutability If
ElectricCar
publicly inherits
Vehicle
, every operation promised by
Vehicle
must remain meaningful for
ElectricCar
. This is an **is-a** relationship, not merely code reuse.
## A class hierarchy makes shared promises and specialization explicit ~~~text Vehicle ├── Bicycle └── Car └── ElectricCar ~~~ The base owns common behavior; derived classes add or refine specialized behavior.
## A small base interface leaves derived types to specialize ~~~cpp class Vehicle { public: int wheels() const { return 4; } }; class ElectricCar : public Vehicle { public: int batteryPercent() const { return 80; } }; ~~~ A
protected
member would be hidden from ordinary callers but accessible inside derived members. Prefer a small function over exposing raw state. Passing a derived object to a base reference tests substitutability.
## Base construction completes before derived construction 1. Base members are initialized. 2. The base constructor runs. 3. Derived members are initialized. 4. The derived constructor runs. Destruction occurs in the reverse order.
## Composition models has-a without forcing substitutability A
Car
has an
Engine
; it is not an engine. Composition usually exposes fewer dependencies and is easier to change. Inheritance is appropriate only when substitutability is defensible.
## Use inheritance for is-a contracts and composition for owned parts - Friend access is narrow and explicit. - Public inheritance models is-a and substitutability. - A hierarchy shares a justified base abstraction. - Base construction precedes derived construction. - Prefer composition for has-a relationships.