Search code examples
c++classscopeusingnamed-scope

What Does Specifying a Class Name in a using Statement Do?


Given the following:

namespace Foo{
class Bar{
    static const auto PRIVATE = 0;
    const int private_ = 1;
    void ptivateFunc() { cout << 2; }
public:
    static const auto PUBLIC = 3;
    const int public_ = 4;
    void publicFunc() { cout << 5; }
};
}

The statement using Foo::Bar; compiles... But I'm not sure what it's providing me access to. Can anyone explain what the point of that statement would be and what it would give me access to with respect to Bar versus simply doing a using namespace Bar?


Solution

  • From cppreference:

    using ns_name::name; (6)
    (...)
    6) using-declaration: makes the symbol name from the namespace ns_name accessible for unqualified lookup as if declared in the same class scope, block scope, or namespace as where this using-declaration appears.

    using namespace ns_name; (5)
    5) using-directive: From the point of view of unqualified name lookup of any name after a using-directive and until the end of the scope in which it appears, every name from namespace-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and namespace-name.

    So basically you can write Bar instead of Foo::Bar outside of the namespace Foo (but inside the scope of the using-declaration), while other symbols from the namespace Foo still need the full name.

    If you use using namespace Foo you can access all symbols in Foo by their local name without the explicit Foo::.