Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a class method call a global function with the same name?

The following code shows a function call another function.
Both have the same name, but different signatures.
This works as expected.

//declarations
void foo();
void foo(int);

int main(){
  foo();
}

//definitions
void foo(){
    foo(1);
}
void foo(int){}

The only difference I will make now, is wrap one of the functions into a structure:

//declarations
struct Bar{
    void foo();
};
void foo(int);

int main(){
  Bar bar;
  bar.foo();
}

//definitions
void Bar::foo(){
    foo(1);
}
void foo(int){}

This fails to compile.

In member function ‘void Bar::foo()’:
error: no matching function for call to ‘Bar::foo(int)’
         foo(1);
              ^
note: candidate: void Bar::foo()
     void Bar::foo(){
          ^
note:   candidate expects 0 arguments, 1 provided

I don't understand why it wants to call foo(int) as a method, when the global function exists.
It doesn't mention anything about ambiguity, it just can't find the function.

Why is this happening, and how can I fix it?

side note: I'm wrapping old C code in a C++ wrapper, and most of the C++ methods are calls to the global C functions which pass in the wrapped struct implicitly. It's a similar situation to what is happening above (in terms of compiler errors).

like image 764
Trevor Hickey Avatar asked Oct 22 '15 23:10

Trevor Hickey


People also ask

Can class and function have same name in C++?

In C++, function overloading is possible i.e., two or more functions from the same class can have the same name but different parameters.

What is a function with the same name as another function in its class called?

Ans. A member function with the same name as its class is called constructor and it is used to initialize the objects of that class type with a legal initial value.

How do you call global function in CPP?

::my_foo(val); This tells the compiler you want to call the global function and not the local function.

Can you call a function outside the class?

The definition of member functions can be inside or outside the definition of class. If the member function is defined inside the class definition it can be defined directly, but if its defined outside the class, then we have to use the scope resolution :: operator along with class name alng with function name.


1 Answers

The member function is hiding the global. It finds the name in the class context, therefore it not continue to search it in other contexts.

You need to call it like this:

::foo(1);

Another solution is to use forward declaration inside the function, like this:

void Bar::foo()
{
    void foo(int);
    foo(1);
}

As Praetorian suggests, here is another option:

void Bar::foo()
{
    using ::foo;
    foo(1);
}
like image 130
SHR Avatar answered Sep 19 '22 04:09

SHR