< previous page page_929 next page >

Page 929
private:
    .
    .
    .
};
Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic (run-time) binding of a function to an object. That is, the determination of which function to call is postponed until run time. (Note that to make Write a virtual function, the word virtual appears in one place onlythe Time class declaration. It does not appear in the Write function definition that is located in the time.cpp file, nor does it appear in any descendant classsuch as ExtTimethat overrides the Write function.)
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Dynamic Binding The run-time determination of which function to call for a particular object.
Virtual functions work in the following way. If a class object is passed by reference to some function, and if the body of that function contains a statement
formalParam.MemberFunc(  );
then
1. If MemberFunc is not a virtual function, the type of the formal parameter determines which function to call. (Static binding is used.)
2. If MemberFunc is a virtual function, the type of the actual parameter determines which function to call. (Dynamic binding is used.)
With just one wordvirtualthe difficulties we encountered with our Print function disappear entirely. If we declare Write to be a virtual function in the Time class, the function
void Print( /* in */ Time& someTime )
{
    .
    .
    .
    someTime.Write();
    .
    .
    .
}

 
< previous page page_929 next page >