# Lecture 20: Select runtime behavior through safe interfaces ## Select behavior from the runtime object safely **Instructor:** [Dr. Debasish Pattanayak](https://drdebmath.github.io)
## Public and private inheritance make different interface promises - Public inheritance preserves the base interface and models is-a. - Private inheritance is an implementation technique and does not promise substitutability. Composition is usually clearer than private inheritance.
## Virtual inheritance shares one common base in a diamond Multiple inheritance gives one derived class more than one direct base. In a diamond, virtual inheritance can share one common base subobject. Use these mechanisms only when the domain model genuinely requires them; they are not the starting point for polymorphism.
## A virtual function selects the override from the runtime type ~~~cpp class Shape { public: virtual double area() const = 0; virtual ~Shape() = default; }; class Square : public Shape { double side; public: explicit Square(double s) : side(s) {} double area() const override { return side * side; } }; ~~~
## A virtual destructor makes base-pointer deletion safe ~~~cpp std::unique_ptr
shape = std::make_unique
(4.0); double result = shape->area(); ~~~ The virtual destructor makes deletion through the base interface safe. Lecture 21 will place differently typed objects in one owning container.
## A factory centralizes construction behind the interface ~~~cpp std::unique_ptr
makeSquare(double side) { return std::make_unique
(side); } ~~~ A factory returns an abstraction while choosing a concrete type in one place.
## Every derived type must pass the base-level tests For every derived type, test: - calls made through a base reference; - cleanup through base ownership; - invalid constructor inputs; - behavior added by a new derived type without changing existing callers.
## Interfaces, safe ownership, and substitutability earn polymorphism - Public inheritance promises substitutability. - Dynamic dispatch selects an override at runtime. - Polymorphic bases need virtual destructors. - Own derived objects with smart pointers. - Factories separate construction choice from use.