# Lecture 21: Separate polymorphism, ownership, and graph links ## Store varied behavior behind one safe interface **Instructor:** [Dr. Debasish Pattanayak](https://drdebmath.github.io)
## A heterogeneous container owns varied objects through one interface ~~~cpp std::vector
> shapes; shapes.push_back(std::make_unique
(2.0)); shapes.push_back(std::make_unique
(3.0)); ~~~ Concrete types differ; ownership and the operation contract are uniform.
## Algorithms stay reusable through promised interface operations ~~~cpp double totalArea(const std::vector
>& shapes) { double total = 0.0; for (const auto& shape : shapes) total += shape->area(); return total; } ~~~ Adding a new shape does not change this traversal.
## An object graph separates entities from their relationships ~~~text [Indore] --rail--> [Ujjain] | road v [Dewas] ~~~ Vertices model entities; edges model relationships. The graph is a structure, not an external visualization service.
## Graph storage follows the operations the application needs - Adjacency list: store outgoing neighbors for each vertex. - Edge list: store relationships as records. - Matrix: direct pair lookup but quadratic storage. Polymorphism is useful only when vertex or edge behavior genuinely varies.
## Ownership stays independent from graph connectivity Let the graph own vertices and edges with smart pointers. Store non-owning IDs or indices for relationships when possible. Avoid cycles of shared ownership; graph connectivity is not the same as memory ownership.
## Add one actor without changing the controller Add a
WeightedEdge
with a cost and a
ScheduledEdge
with departure time. Write one traversal that prints every edge through the base interface, then identify which operations do not require polymorphism.
## Polymorphism, ownership, and graph links stay independently testable - Heterogeneous containers combine a base contract with safe ownership. - Algorithms depend on operations, not concrete type names. - Object graphs separate entities from relationships. - Pick adjacency representation from required operations. - Keep graph links separate from ownership links.