Sams Teach Yourself C++ in 21 Days

(singke) #1
When a virtual function is created in an object, the object must keep track of that func-
tion. Many compilers build a virtual function table, called a v-table. One of these is kept
for each type, and each object of that type keeps a virtual table pointer (called a vptr or
v-pointer), which points to that table.
Although implementations vary, all compilers must accomplish the same thing.
Each object’s vptr points to the v-table that, in turn, has a pointer to each of the virtual
functions. (Note: Pointers to functions are discussed in depth on Day 15, “Special
Classes and Functions.”) When the Mammalpart of the Dogis created, the vptr is initial-
ized to point to the correct part of the v-table, as shown in Figure 12.3.

396 Day 12


FIGURE12.3
The v-table of a
Mammal.
Mammal

Move

VPTR
&
&Speak

When the Dogconstructor is called, and the Dogpart of this object is added, the vptr
is adjusted to point to the virtual function overrides (if any) in the Dogobject (see
Figure 12.4).

FIGURE12.4
The v-table of a Dog.
Mammal

Dog

Mammal: Move ( )

VPTR
&

&Dog: Speak ( )

When a pointer to a Mammalis used, the vptr continues to point to the correct function,
depending on the “real” type of the object. Thus, when Speak()is invoked, the correct
function is invoked.

Trying to Access Methods from a Base Class................................................


You have seen methods accessed in a derived class from a base class using virtual func-
tions. What if there is a method in the derived class that isn’t in the base class? Can you
Free download pdf