In C++ why can I access a function defined in a namespace without namespace qualifer

98 Views Asked by At

I have a namesapce ns. Within ns I defined a class and a function. I further defined the function to be a friend of the class so that the function can access a private variable of the class. In the main program, I succeeded in calling the function without quflifying it with ns::. Please see the code for details.

#include <iostream>

namespace ns {
    class MyClass;
    void print_fn(const MyClass & c);
}

namespace ns {
    class MyClass {
    private:
        int _a;
    public:
        MyClass(int a): _a(a) {}

        friend void print_fn(const MyClass & c);
    };

    void print_fn(const MyClass & c){
        std::cout << c._a << std::endl;
    }
}


int main()
{
    ns::MyClass c(10);
    print_fn(c);

    return 0;
}
1

There are 1 best solutions below

0
Vlad from Moscow On

This is called Argument Dependent Lookup.

The compiler searches the function in the namespace where its arguments were declared.

You can disable the argument dependent lookup the following way

 ( print_fn )(c);

In this case the compiler issues an error that the function print_fn is not found.