Virtual Functions and Polymorphism

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

  1. Time with Time Zone
  2. Payroll

Virtual Function Usage

  1. To obtain dynamic binding, you must use pass-by-reference when passing a class object to a function.
  2. In the declaration of a virtual function, the word virtual appears only in the base class, not in any derived class.
  3. If a base class declares a virtual function, it must implement that function, even if the body is empty.
  4. A derived class is not required to provide its own reimplementation of a virtual function.
  5. 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

  1. Default constructor
  2. Copy constructor
    	Time startTime(8, 30, 0);
    	Time lectureTime(startTime);
    
  3. Destructor
  4. Assignment Operator =
    	Time startTime(8, 30, 0);
    	Time lectureTime=startTime;
    

Case Study

Shape