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();
    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?


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.

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.

Need Your Help

package update in ubuntu on vitual box

ubuntu configuration virtualbox

while following one of the tutorials I needed to install a curl package.

MySQL licence when developing a website?

mysql database jsp

I want to create a website in JSP and the database will be MySQL. I will host the website on the internet. Is it required to obtain any licence to develop them on my machine?