(Latest Revision: 10/03/2000)
ch08_Notes02_VirtFuncs
ch08 Notes on Virtual Functions
Notes on the text of chapter 8 -- VIRTUAL FUNCTIONS
As we noted in the discussion of inheritance, it can be
difficult or impossible for a compiler to determine at compile
time what the data type of an object is. In particular, if
this segment of code is executed:
sphereClass sphere ;
sphereClass * SPtr = &sphere ;
ballClass ball ;
SPtr->DisplayStatistics();
SPtr = &ball ;
SPtr->DisplayStatistics();
or worse, if this segment of code is executed:
sphereClass * X[26] ; // 26 pointers
init (X) ; // Some are made to point to balls, others to plain spheres.
int n ;
cin >> n ;
// how does the compiler know whether *X[n] is a ball?
X[n]->DisplayStatistics() ;
Then the sphereClass version of DisplayStatistics may be
invoked both times.
The virtual keyword is basically a directive that the programmer
uses to mark a method in a base class. It warns the compiler
that a derived class may revise the method. When the compiler
gets this warning, it generate code that uses dynamic binding
at runtime to aid in choosing the right version of the method
to execute.
DisplayStatistics is an example of a polymorphic method: The
meaning of the method depends on the data type of the object to
which the message is sent. (A ball responds to a message to
display itself one way, a plain sphere another way, a pyramid
still another.)
If you define a method in a base class whose definition will be
changed by some derived class or classes, begin the declaration
of the method in the base class with the keyword virtual. For
example:
class sphereClass
{
public:
... // everything as before, except DisplayStatistics
virtual void DisplayStatistics() const ;
{
// put definition of function here.
}
... // all the rest of the declarations
} ; // end class
(Unfortunately this forces the designer of the base class to
worry about the possible derived classes that may be invented.)