Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class name be used as a namespace?

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?

like image 200
Stefan Stanković Avatar asked Nov 29 '15 00:11

Stefan Stanković


1 Answers

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.

like image 66
M.M Avatar answered Oct 23 '22 02:10

M.M