- Polymorphism : the ability for objects of different classes related by inheritance to
respond differently to the same member function call.
- Polymorphism is implemented via virtual functions.
Static (compile-time) Binding
Time startTime(8, 30, 0);
ExtTime endTime(10, 45, 0, CST);
startTime.Write();
cout << endl;
endTime.Write();
cout << endl;
void Print( Time someTime )
{
cout << "******************" << endl;
cout << "** The time is ";
someTime.Write();
cout << endl;
cout << "******************" << endl;
}
Time startTime(8, 30, 0);
ExtTime endTime(10, 45, 0, CST);
Print(startTime);
Print(endTime);
call by value --> slicing problem, time zone not printed
void Print( Time& someTime )
call by reference --> time zone still not printed,
compiler uses static (compile-time) binding
of the operation ( Time::Write ) to the object
Dynamic (run-time) Binding
class Time
{
public:
.
.
virtual void Write() const;
.
.
private:
.
.
}
Examples
- Time with Time Zone
- Payroll
Virtual Function Usage
- To obtain dynamic binding, you must use pass-by-reference when passing a class object to a function.
- In the declaration of a virtual function, the word virtual appears only in the base class, not in any derived class.
- If a base class declares a virtual function, it must implement that function, even if the body is empty.
- A derived class is not required to provide its own reimplementation of a virtual function.
- A derived class cannot redefine the function return type of a virtual function.
Member Function Search Order
Class Type |
Member Function Type |
Search Order |
Derived |
Normal |
Derived->base |
Base |
Normal |
Base |
Base |
virtual |
Derived->base |
Automatically Generated Member Functions
- Default constructor
- Copy constructor
Time startTime(8, 30, 0);
Time lectureTime(startTime);
- Destructor
- Assignment Operator =
Time startTime(8, 30, 0);
Time lectureTime=startTime;
Case Study
Shape