Overriding base class methods
Not logged in

Overriding base class methods

A derived class can declare a method to override a method in its base class. The method declaration in the derived class must exactly match the method in the base class in order to override it. That means it must have the same return type, name, arguments and the const keyword if it has been used.

Care must be taken when overriding base class methods to avoid unintentionally hiding overloaded methods - a single overriding method in a derived class will hide all overloaded methods of that name in the base class!

For instance, the base Mammal class, listed below, contains two overloaded methods named walk. These require no argument and one argument respectively. The derived Cat class, listed on the opposite page, creates an overriding method named walk, with no arguments. This hides both walk methods in the base class.

Additionally the Cat class contains a method named speak that will override the method of the same name in the Mammal base class whenever it is called from the main program.