Function Overriding

Specialization by function overriding

An inheritance hierarchy shows how more specialized classes are derived from more general classes. We have already seen specialization through the addition of new methods and data members in a derived class (ZonedTime).
Another mechanism for specialization is overriding base class member functions.

This is achieved by defining a derived class method with the exact same signature as a base class method. The derived class method hides the base class method from the user.

Overriding is not overloading


Recall that overloading a function means using the same function name, but with different parameters.
Overriding a function means redefining a function using the same name and parameters (i.e., signature), but with a different implementation. (This is possible only with inheritance.)

Overriding Example

In our Time/ZonedTime example, ZonedTime extended Time by adding new methods and data members. But suppose ZonedTime was defined a little differently.

Suppose instead of having PrintZonedTime( ), the ZonedTime class redefined PrintTime( ).

class ZonedTime: public Time { public: enum ZoneType = {EST, CST, MST, PST, EDT, CDT, MDT, PDT}; ZonedTime(int hour = 0, int minute = 0, int second = 0, ZoneType zone = EST); void SetZoneTime (int hour, int minute, int second, ZoneType zone); void PrintTime( ) const; // function overriding private: ZoneType m_zone; }; void ZonedTime::PrintTime ( ) const { static string zoneString[8] = {"EST", "CST", "MST", "PST", "EDT", "CDT", "MDT", "PDT" }; Time::PrintTime( ); // explicit call cout << zoneString[m_zone]; } The existence of PrintTime( ) in the ZonedTime (derived) class "hides" the existence of PrintTime( ) in the Time (base) class from the user. int main ( ) { ZonedTime zTime (12, 0, 0); // noon, EST zTime.Increment( ); // an inherited method zTime.PrintTime( ); // overriding -- calls ZonedTime::PrintTime return 0; }