Johnny Pauling
Johnny Pauling

Reputation: 13407

C++ calling the same function with scope operator - is it useful?

I know that the :: operator in C++ is the scope-resolution, but what's the purpose of calling a function inside a class with it like this

class MyClass
{
 int myFunc(int argument)
 {
     // do some stuff
     return (::myFunc(another_argument));
 }
}

is there a practical reason? Is a "this" subintended in that?

Upvotes: 3

Views: 137

Answers (1)

111111
111111

Reputation: 16148

If you had a use case like this:

//in the global namespace
int myFunc(int);

//elsewhere
class MyClass
{
 int myFunc(int argument)
 {
     // do some stuff
     return (::myFunc(another_argument));
 }
}

Here we need to discern between the member function and the free function. This is quite a common occurrence when wrapping C libraries.

In this case :: forces the compile to pick the version that resides in the global namespace rather than the member function which would end up recursively calling itself.

Upvotes: 9

Related Questions