Sign in to follow this  

question about namespaces

This topic is 1804 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can you use the same namespace in 2 files? For ex:

 

test.h

 

namespace x

{

int i;

};

 

test2.h

namespace x

{

int u;

};

 

I guess you have you have to include test.h in test2 right? I just find this kinda peculiar because untill now I never really used namespaces a lot,and it's weird for me to see you can make definitions in the same namespace in different files.

 

Anyway,am I correct?

Share this post


Link to post
Share on other sites
Nope, namespaces are "open" in that you can add a name to a namespace in as many different files as you want, and they don't need to include any of the others. All the standard library headers do that.

C# has partial classes which allow you to do the same with a class as well.

Share this post


Link to post
Share on other sites

wait...so can i add variables and functions to the same namespace from different header files? 

Share this post


Link to post
Share on other sites
There is one exception: it's undefined for a C++ program to add to namespace std with a few exceptions like adding specializations for existing library classes.

Share this post


Link to post
Share on other sites
Downside is you can have headscratching moments whereby you cant add a string as a key on a map even though the compiler knows about a string (forward declaration I guess), but it doesn't know about string::operator< because you didn't #include <string>

Share this post


Link to post
Share on other sites

This is useful for forward declarations. For example, in you header file, you can do:

 

namespace XXX {
    class YYY;
};

And then you can use declarations with references to XXX::YYY in your header file, without having to include the header file where the real declaration is.

Share this post


Link to post
Share on other sites
Sign in to follow this