Virtual Member Functions and Dynamic Binding

Let’s revisit the process of invoking a method with a reference or pointer. Consider the following code:

BrassPlus ophelia;    // derived-class objectBrass * bp;           // base-class pointerbp = &ophelia;        // Brass pointer to BrassPlus objectbp->ViewAcct();       // which version?

As discussed before, if ViewAcct() is not declared as virtual in the base class, bp->ViewAcct() goes by the pointer type (Brass *) and invokes Brass::ViewAcct(). The pointer type is known at compile time, so the compiler can bind ViewAcct() to Brass::ViewAcct() at compile time. In short, the compiler uses static binding for nonvirtual methods.

But if ViewAcct() is declared as virtual in the base class, bp->ViewAcct() ...

Get C++ Primer Plus 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.