Calling a Hidden Virtual through the Base Class

Given the classes above, let’s look at several different ways to call these functions:

Base bobj;  D1 d1obj; D2 d2obj;Base *bp1 = &bobj, *bp2 = &d1obj, *bp3 = &d2obj;bp1->fcn(); // virtual call, will call Base::fcn at run timebp2->fcn(); // virtual call, will call Base::fcn at run timebp3->fcn(); // virtual call, will call D2::fcn at run timeD1 *d1p = &d1obj; D2 *d2p = &d2obj;bp2->f2(); // error: Base has no member named f2d1p->f2(); // virtual call, will call D1::f2() at run timed2p->f2(); // virtual call, will call D2::f2() at run time

The first three calls are all made through pointers to the base class. Because fcn is virtual, the compiler generates code to decide at run time which version to ...

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.