egst
egst

Reputation: 1804

Specifying namespaces explicitly inside method definitions

Let's suppose I have a namespace Foo and I have declared a class Bar inside of it with a constructor inheriting a class Base with its constructor along with some other class Baz with a publicly accessible method boo():

namespace Foo {
    class Baz {
    public:
        void boo();
    };
    class Base {
    public:
        Base();
    };
    class Bar: public Base {
    public:
        Bar();
    };
}

Now I want to define the Bar constructor in my implementation as follows:

Foo::Bar::Bar(): Foo::Base::Base() {
    Foo::Baz::boo();
}

It appears as though it's OK to write it down like this:

Foo::Bar::Bar(): Base() {
    Baz::boo();
}

Meaning that once I specify the namespace in Foo::Bar::Bar() explicitly, there is no need to specify it later in the definition of this method.

Does it work like that everywhere from the explicit mentioning of the namespace up to the end of the definition?

Upvotes: 0

Views: 89

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

If we look at your Bar constructor definition:

Foo::Bar::Bar(): Base() {
    Baz::boo();
}

Once the declaration-part of the constructor (Foo:::Bar::Bar) have been read by the compiler, it knows the scope and it's no longer needed.

A more interesting example would be e.g.

namespace Foo
{
    struct Baz {};

    struct Bar
    {
        Baz fun(Baz);
    };
}

Foo::Baz Foo::Bar::fun(Baz)
{
    // Irrelevant...
}

Now, for the definition of the structure itself, Baz doesn't need any namespace-qualifier since it's defined in the namespace and all the symbols of the namespace is available directly.

The definition of the function fun is a different. Because it's not defined inside the namespace, we need to fully qualify the Baz structure for the return type. And the same for the actual function-name. But then like before once that part is read and parsed by the compiler, it knows the scope and knows that the argument Baz is really Foo::Baz.

You can read more about name lookup in this reference.

Upvotes: 3

Related Questions