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:
When
function1
is called by itself outside offunction2()
, it is actually a function pointer tofunction1()
.Inside the scope of
function2
, whenint function1
is declared, 'function1
the variable' shadows 'function1
the function pointer'.When
function1()
is called insidefunction2()
, it is assumingfunction1
is the variable and is giving an error.This is fixed by calling
Base::function1();
insidefunction2()
.
My question is this: Why doesn't the compiler give an error when declaring int function1;
? Shouldn't this not be allowed?
-Wshadow
, or whatever your compiler calls it. – Mbfunction2
it resolves to a variable of typeint
, and you can't call a variable of typeint
. – Nacredfunction1
was a functor or a lambda though, that would be ambiguous. And it would get very confusing and have a fair number of ambiguous usage cases depending on how you usefunction1
, so it's easier/nicer to have simpler name lookup rules which prohibit this instead of trying to figure out your intention. – Hedgehop