The Secret Life of C++: Day 2: Virtual Methods
As we have seen, calling non-virtual methods with objects isn't
very complicated. Now lets talk about virtual methods and subclassing.
Virtual Methods - Call by Pointer/Reference
How do virtual methods work? With a vtable. What a vtable? Lets
look at an example:
basic-vtable.cc,
basic-vtable.s,
basic-vtable.listing.
- _ZTV8onefield
- A pointer to the VTable of the onefield object.
- _ZTI8onefield
- A pointer to the typeinfo structure for onefield.
- _ZTVN10__cxxabiv117__class_type_infoE+8
- Pointer to the
VTable for the implementation object of class_type_info.
Virtual Methods - Overriding
Lets do an example where we override a virtual method:
subclass-vtable.cc,
subclass-vtable.s,
subclass-vtable.listing.
- _ZTV17onefield_subclass
- This is the vtable for onefield_subclass.
As we can see, the subclass vtable has the same entries as the
superclass, but where they are overridden we see the subclass
methods replacing the superclass methods where appropriate.
Virtual Methods - Call by "Value"
When you call a virtual method on a local or temporary variable,
the compiler really does know the type of the variable, and so it
doesn't have to go through the vtable. This is a useful
optimization. It can be seen in the basic-vtable example above.
It is also why you have to make sure to pass a
subclass into a method expecting a superclass by reference, not by
copyconstructing an instance of the superclass. Becuase the later
technique will cause the superclass functions to get called,
rather than the subclass ones, even if they are virtual.
Pure Virtual Methods
Pure virtual methods are just funny entries in the vtable.
Specifically pointers to __cxa_pure_virtual. An example:
vtable-null.cc,
vtable-null.s,
vtable-null.listing.
Virtual Destructors
You want a virtual destructor becuase otherwise someone might
delete your object when they have a pointer to a superclass, and
your destructor won't get run. Simple as that.
Subclasses
To see subclasses that add data values, we can look back at our
subclass-vtable example:
subclass-vtable.cc,
subclass-vtable.s,
subclass-vtable.listing.
Richard Tibbetts
Last modified: Wed Jan 21 17:36:31 EST 2004