Overloading, Hiding, and Overriding
First, let us recall the definitions of two terms that often get confused:
- When two or more versions of a function foo exist in the same scope (with different signatures), we say that foo has been overloaded.
- When a virtual function from the base class also exists in the derived class, with the same signature, we say that the derived version overrides the base class version.
Example 6.18 demonstrates overloading and overriding and introduces another relationship between functions that have the same name.
Example 6.18. src/derivation/overload/account.h
[ . . . . ] class Account { protected: static const int SS_LEN = 80; public: virtual void deposit(double amt); virtual const char* toString() const; virtual const char* toString(char delimiter); <-- 1 protected: unsigned m_AcctNo; double m_Balance; char m_Owner[SS_LEN]; }; class InsecureAccount: public Account { public: const char* toString() const; <-- 2 void deposit(double amt, QDate postDate); <-- 3 }; [ . . . . ] (1)overloaded function (2)Overrides base method and hides toString(char). (3)Does not override any method, but hides all Account : : deposit() methods. |
Function Hiding
A member function of a derived class with the same name as a function in the base class hides all functions in the base class with that name. In addition:
- Only the derived class function can be called directly.
- The class scope resolution operator may be used to call hidden base functions explicitly.
The client code in Example 6.19 shows how to call a base class function that has been hidden by a derived class function with the same name.
Example 6.19. src/derivation/overload/account.cpp
#include "account.h" #include #include using namespace std; int main() { InsecureAccount acct; acct.deposit(6.23); <-- 1 acct.m_Balance += 6.23; <-- 2 acct.Account::deposit(6.23); <-- 3 return 0; } (1)Error! No matching functionhidden by deposit(double, int) (2)Error! Member is protected, inaccessible. (3)Hidden does not mean inaccessible. We can still access hidden public members via scope resolution. |