13

I remember being told that C++ classes have their own namespaces, and that the class name could be used as a namespace for scope resolution, like this:

// Example.h
class Example {
    void Private();
public:
    void Public();
}

and, later in a manner similar to this:

// Example.cpp
#include "Example.h"
using /*namespace*/ Example;
void Private() {}
void Public() {}

instead of:

// Example.cpp
#include "Example.h"
void Example::Private() {}
void Example::Public() {}

but I couldn't find neither an explanation nor an example of that in my books. A brief Google search was also a dead-end. Is this a real thing?

Stefan Stanković
  • 628
  • 2
  • 6
  • 17

2 Answers2

15

No, namespaces and classes are different.

However, namespaces and classes both introduce a scope which may be referred to using the scope resolution operator :: .

The using namespace N; declaration can only apply to namespaces. It's not possible to do something similar for a class. You can only do using Example::x; for specific names x inside Example to import them one by one.

When providing the member function body out-of-line, you must write Example::Private(), there is no alternative.

M.M
  • 138,810
  • 21
  • 208
  • 365
-1

Yes, Every class has its own namespace that everything part of the class declaration belongs to.

You may employ the using directive as you indicate as explained here.

It should be noted that you cannot declare a namespace with the same name as a class as shown here:

namespace fubar
{
    class snafu
    {
        ...
    };
}
// Cannot do stuff below (ERROR)
namespace fubar::snafu;
{
    // this is not valid, once a class always a class
    // once a namespace, always a namespace
    // a class makes a namespace also but never JUST a namespace
}

Do be careful though. 'Using' too much can play real tricks on you and those who inherit your code.

Ken Clement
  • 748
  • 4
  • 13
  • 1
    I am afraid you didn't understand me, despite the examples. There is not a single example/explanation [here](http://en.cppreference.com/w/cpp/language/using_declaration) that depicts the usage I mentioned. Feel free to prove me wrong with an example, I'd appreciate it. – Stefan Stanković Nov 29 '15 at 00:48