Calls to Virtual Functions May Be Resolved at Run Time
When a virtual function is called through a reference or pointer, the compiler generates code to decide at run time which function to call. The function that is called is the one that corresponds to the dynamic type of the object bound to that pointer or reference.
As an example, consider our print_total
function from §15.1 (p. 593). That function calls net_price
on its parameter named item
, which has type Quote&
. Because item
is a reference, and because net_price
is virtual, the version of net_price
that is called depends at run time on the actual (dynamic) type of the argument bound to item
:
Quote base("0-201-82470-1", 50);print_total(cout, base, 10); // calls Quote::net_priceBulk_quote ...
Get C++ Primer, Fifth Edition 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.