11.4. Virtual Functions

It's not always possible at compile time to determine which derived object a base class pointer or reference refers to. Virtual functions provide resolution at run time. This section explores dynamic binding and its implementation with virtual functions.

Dynamic Binding

Both Person and Student have separate output() definitions that we call with objects, references, or pointers. A more natural approach overloads operator<<() to display the attributes of Person and Student objects.

ostream & operator<<(ostream & os, const Person & p) {
   p.output(os);
   return os;
}

Since the second argument matches both a Person object (exact match) and a Student object (derived to base standard conversion), this approach is appealing. Why? ...

Get Navigating C++ and Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.