Friday, April 4, 2014

Name hiding in C++


What is name hiding in C++?


Lets talk about  3 points :
  • Overriding
  • Overloading
  • Hiding
In Thinking in C++, 2e, Volume 1 (pages 632:646), Bruce Eckel had something similar to say, but he did specifically say overriding:
The redefinition of a virtual function in a derived class is usually called overriding
Overloading allows you to provide more than one definition for a function within the same scope.
Page 130 from C++ Programming in Easy Steps also mentions:
The technique of overriding base class methods must be used with caution however, 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.

Let us explain through an example. In C++, when you have a class with an overloaded method, and you then extend and override that method, you must override all of the overloaded methods.
For example:
class FirstClass {
    virtual void MethodA (int);
    virtual void MethodA (int, int);
void FirstClass::MethodA (int i) {
    std::cout << "ONE!!\n";
void FirstClass::MethodA (int i, int j) {
    std::cout << "TWO!!\n";

This is a simple class with two methods (or one overloaded method). If you want to override the one-parameter version, you can do the following:
class SecondClass : public FirstClass {
    void MethodA (int);
void SecondClass::MethodA (int i) {
    std::cout << "THREE!!\n";
int main () {
    SecondClass a;
    a.MethodA (1);
    a.MethodA (1, 1);

However, the second call won't work, since the two-parameter MethodA is not visible:
error: no matching function for call to ‘SecondClass::MethodA(int, int)’
note: candidates are: virtual void SecondClass::MethodA(int)

That is name hiding.Of-course, this is a basic post, but you would like to go deep, read more:



Post a Comment