Home > OS >  What is the difference between calling foo() and ::foo() within a C class member function?
What is the difference between calling foo() and ::foo() within a C class member function?

Time:06-15

I am looking at someone else's C code (note I am not fluent in C ).

Within the class, there is this member function:

void ClassYaba::funcname()
{
    ...
    ::foo();
    ...
}

There is no member function within that class's namespace named foo, but aside from that, what is the difference between ::foo() and foo() (no leading colons)?

CodePudding user response:

When you call

foo();

C will search for something named foo in the following order:

  1. Is there something with this name declared within the class?
  2. Is there something with this name in a base class?
  3. Is there something with that name in the namespace in which the class was declared? (And, if not, is there something with that name in the parent namespace of that namespace, etc.?)
  4. Finally, if nothing was found, is there something with that name in the global namespace?

On the other hand, writing

::foo();

will make C look for something purely in the global namespace.

If there is nothing named foo in your class, any of its base classes, or any namespaces foo was declared inside of, then there's no difference between the two approaches.

  • Related