What is the difference between calling foo() and ::foo() within a C++ class member function?
Asked Answered
T

1

5

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)?

Townshend answered 14/6, 2022 at 22:15 Comment(1)
With foo(), unqualified name lookup is performed. With ::foo(), qualified name lookup is performed. Depending on surrounding context (not shown in example), the two may find the same or different entities.Candiecandied
G
7

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.

Gd answered 14/6, 2022 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.