Wednesday 29 April 2015

What is name hiding in C++?


Let us understand name Hiding concept with an example:


#include<iostream>
#include<conio.h>
using namespace std;

class A
{
public:

    void fun()
    {
    }
    void fun1()
    {
    }
};

class B:public A
{
public:
    void fun()
    {
    }
    void fun1(int x)
    {
    }
};

void main()
{
    B obj;
    obj.fun();
    obj.fun1();
}


in the above program it looks like the call of function fun1() in the main should run fine


  • But, in reality that method call results in an error which will say something like “error: no matching function for call to "error C2660: 'B::fun1'"
  • Why would it return that error? The Class B clearly derives from the Class A so it looks like the Class B object in the main function should have access to the fun1() function declared inside the Class A in addition to the fun(int) that accepts an integer  and is defined inside the Class B.



The reason the function call above results in an error is because of a property of C++ called name hiding


Let understand more about Name Hiding by taking another example:

#include<iostream>
#include<conio.h>
using namespace std;

class A
{
public:

    void fun1(string s)
    {
    }
};

class B:public A
{
public:
    void fun1(int x)
    {
    }
};

void main()
{
    string s;
    B obj;
    obj.fun1(s);

}

once again it look life there will be no issue in function fun1() calls from main function.
But when you try to compile your code it will throw an error " C2664: 'B::fun1' : cannot convert parameter 1 from 'std::string' to 'int'"


So, what should be done here?

Functions in derived classes with the same name as the functions in the parent classes, but that do not override the parent classes’ function are considered to be bad practice because it can result in errors just like the one above. So, having a function like fun1()  above is considered to be bad practice. This is technically not method overloading either, because overloading functions is done within the same class – not in an inheritance hierarchy.


The reason it’s bad practice is because it leads to ambiguity, and it’s much easier to just give the functions different names instead.

Solution to Name Hiding Problem

 The problem of name hiding can be solved ,All we have to do is implement the using keyword. let us understand by help of an example:


#include<iostream>
#include<conio.h>
using namespace std;

class A
{
public:

    void fun1(string s)
    {
    }
};

class B:public A
{
public:
    void fun1(int x)
    {
    }
    using A::fun1;
};

void main()
{
    string s;
    B obj;
    obj.fun1(s);

}



When we redeclare someFunction in the scope of Class B (with the “using” keyword), it makes both versions of that function (from both Class A and Claas B) visible in just the Classs B

0 comments:

Post a Comment