Reason for C++ member function hiding [duplicate]

Name lookup works by looking in the current scope for matching names, if nothing is found then it looks in the enclosing scope, if nothing is found it looks in the enclosing scope, etc. until reaching the global namespace.

This isn’t specific to classes, you get exactly the same name hiding here:

#include <iostream>

namespace outer
  void foo(char c) { std::cout << "outer\n"; }

  namespace inner
    void foo(int i) { std::cout << "inner\n"; }

    void bar() { foo('c'); }

int main()

Although outer::foo(char) is a better match for the call foo('c') name lookup stops after finding outer::inner::foo(int) (i.e. outer::foo(char) is hidden) and so the program prints inner.

If member function name weren’t hidden that would mean name lookup in class scope behaved differently to non-class scope, which would be inconsistent and confusing, and make C++ even harder to learn.

So there’s no technical reason the name lookup rules couldn’t be changed, but they’d have to be changed for member functions and other types of name lookup, it would make compilers slower because they’d have to continue searching for names even after finding matching names in the current scope. Sensibly, if there’s a name in the current scope it’s probably the one you wanted. A call in a scope A probably wants to find names in that scope, e.g. if two functions are in the same namespace they’re probably related (part of the same module or library) and so if one uses the name of the other it probably means to call the one in the same scope. If that’s not what you want then use explicit qualification or a using declaration to tell the compiler the other name should be visible in that scope.

Leave a Comment