ntm
ntm

Reputation: 93

Class definition inside namespace

I have a class declaration like so:

// bar.h
namespace foo {
    class bar {
        // members both public and private
    }
}

When I define the class, I would like to do this

// bar.cpp
namespace foo::bar {
    // member definitions
}

Rather than

namespace foo {
    bar::x() {}
    bar::y() {}
    bar::z() {}
}

But I cannot. Why is this? I thought classes declared namespaces, but I must be wrong. Shouldn't the scope operator resolve the namespace scope then the class scope?

I ask because any time you have a class name of non-trivial length, it can become very repetitive to re-type the class name, especially if it has more than a few members. Maybe it's like this to make people define small class interfaces.

Upvotes: 1

Views: 89

Answers (2)

Zac Howland
Zac Howland

Reputation: 15872

First off, your class declaration needs a ; after it:

namespace foo 
{
    class bar 
    {
        // members both public and private
    }; // error without this
}

When you are implementing the class (non-inline), you can do it two ways:

void foo::bar::x() 
{
    // function definition
}

or

namespace foo
{
    void bar::x()
    {
        // function definition
    }
}

Note that bar is a class, not a namespace.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

Why is this? I thought classes declared namespaces, but I must be wrong

You are wrong. :)

Shouldn't the scope operator resolve the namespace scope then the class scope?

It wouldn't be impossible for the language to support this, but it simply doesn't.

Probably because it might get a little confusing, and because the following would be outright lying:

class bar {
    void x();
    void y();
    void z();
};

namespace bar {
    void x() {}
    void y() {}
    void z() {}
}

Really, the analogy to this sort of "inline definitions" that you can do with namespaces, is the inline definitions of member functions:

class bar {
   void x() {}
   void y() {}
   void z() {}
};

Upvotes: 2

Related Questions