Expert C Programming

(Jeff_L) #1

Whoa! If you try it, you'll get output like this:


% CC fruits.cpp


% a.out


peeling a base class fruit


In other words, the Apple-specific method peel() wasn't called, the base class's peel() was!


Explanation


The reason is that C++ demands that you warn it when you start supplanting base class methods with
derived class ones. You warn it by adding the keyword virtual to the base class method that you
might be replacing. You can see now why we were reticent about explaining virtual back on page
301 where we first discovered it. You needed a lot of background information, which we have now
covered.


Handy Heuristic


Virtually Impractical


Why isn't virtual the default? After all, you can always get the method from the base
class by saying:


p->Fruit::peel();


It's pretty much for the same reason that C originally used the register keyword—it's a
dumb optimization. So that every method call doesn't involve an extra indirection at
runtime, you have to tell the compiler which ones do.


The word virtual is a bit of a misnomer in this context. Elsewhere throughout computer science,
"virtual" means letting the user see something that is not really there, and supporting the illusion by
some means. Here, it means not letting the user see something that is really there (the base class
method). A more meaningful (though impractically long) keyword would be


choose_the_appropriate_method_at_runtime_for_whatever_object_t


his_is


or more simply, placeholder.

Free download pdf