Name Hiding - A rarely used C++ feature


Recently one of colleagues encountered a weird compilation error indicating that the method is not found. The code was something like this:



class BaseClass
{
public:
    void Foo();
    void Foo(int, int);
};

class DerivedClass : public BaseClass
{
public:
    void Foo(double);
};

int _tmain(int argc, _TCHAR* argv[])
{
    DerivedClass d;
    d.Foo(10, 10); // error -> 'DerivedClass::Foo' : function
                   // does not take 2 arguments
      return 0;
}

When he was tried to invoke Foo(int, int) method on the object of the DerivedClass, the compiler gave him an error. It was counterintuitive, as the methods seem to be defined correctly in the BaseClass and DerivedClass.
The reason of the compilation error is that methods Foo(int, int) and Foo() in BaseClass got hidden due to the method Foo(double) in the DerivedClass. Few (not all) compilers does give a warning that clearly indicate that the DerivedClass::Foo(double) hides BaseClass::Foo() and BaseClass::Foo(int, int). Other compilers simply tell you that method signature is not matching and would not tell that the BaseClass methods are gone hidden.
There are two ways of fixing this problem:
1.      You can redefine the methods in the DerivedClass by merely delegating the class to the BaseClass



class DerivedClass : public BaseClass
{
public:
    void Foo() // Redefine
    {
        BaseClass::Foo();
    }
    void Foo(int a, int b) // Redefine
    {
        BaseClass::Foo(a, b);
    }
    void Foo(double);
};

2.      You can unhide the methods by using the “using” keyword.


class DerivedClass : public BaseClass
{
public:
    using BaseClass::Foo; // Add it before you overload the method.
    void Foo(double);
};

Note that the use of “virtual” keyword with the Foo method does not change the method hiding behaviour.

Name Hiding - A rarely used C++ feature Name Hiding - A rarely used C++ feature Reviewed by Sourabh Soni on Monday, November 09, 2009 Rating: 5

No comments

Author Details

Image Link [https://3.bp.blogspot.com/-zo21XIdyPqc/VuTrFfUyPhI/AAAAAAAAAO8/EEWTN73XHUA7aTIjuxuBSN-WGaGkNUymA/s1600/sourabhdots3.jpg] Author Name [Sourabh Soni] Author Description [Technocrat, Problem Solver, Corporate Entrepreneur, Adventure Enthusiast] Facebook Username [sourabh.soni.587] Twitter Username [sourabhs271] GPlus Username [#] Pinterest Username [#] Instagram Username [#] LinkedIn Username [sonisourabh] Youtube Username [sonisourabh] NatGeo Username [271730]