O'Reilly logo

C++ Primer Plus by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required