c++scopedeclarationname-lookupname-hiding

Variable name same as function name giving compiler error... Why?


Ran into an interesting issue today and am trying to understand why.

Consider the following:

class Base
{
public:
    Base(){}
    ~Base(){}
    static void function1(){}
        void function2()
        {
           int function1;
           function1 = 0;
           function1();   //<-compiler error
           function1 = 1;
        }
};

I am getting the following error:

expression preceding parentheses of apparent call must have (pointer-to-) function type

I think I understand why I am getting this error:

  1. When function1 is called by itself outside of function2(), it is actually a function pointer to function1().

  2. Inside the scope of function2, when int function1 is declared, 'function1 the variable' shadows 'function1 the function pointer'.

  3. When function1() is called inside function2(), it is assuming function1 is the variable and is giving an error.

  4. This is fixed by calling Base::function1(); inside function2().

My question is this: Why doesn't the compiler give an error when declaring int function1;? Shouldn't this not be allowed?


Solution

  • The local variable overwrites the designator for the method in the local block. Try this->function1() to call it nevertheless.

    Or better yet, rename the one or the other to help people reading your code avoiding confusion (and this includes your future yourself).