What and how does shared namespace in C++ works? Are most of the variables, types, and procedures can be used in shared name space?

Recommended Answers

All 2 Replies

Namespace definitions can be split across multiple files and still have the same name, is that what you mean by "shared"?

// file1.cpp
namespace foo {
    class A {};
    class B {};
}

// file2.cpp
namespace foo {
    class C {};
    class D {};
}

When the project is built, those two namespaces are merged because they have the same name, so concerning membership in the namespace it's as if you wrote it like this:

namespace foo {
    class A {};
    class B {};
    class C {};
    class D {};
}

No such thing as "shared" namespaces. A namespace is a namespace, it doesn't have "shared" attribute. A namespace is just something that better organizes the data, classes, structures and code. It's main purpose it to avoid name clashes. Without namespaces all names must be unique throughout the program (with a few exceptions). If I declared a variable named int x; in one *.cpp file and declared a variable with the same name in another *.cpp file the liker would most likely complain that it found two variables with the same name. But if I put each of those variables in different namespaces then the linker would have no problem because each would actually be different variables.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.