C++ and name spaces

Started by
17 comments, last by ANSI2000 22 years, 4 months ago
What are they and how and when should they be used? Thanks
Advertisement
Namespaces are used so you can have two different things with the same name (like classes).

If you included two headers, firstheader.h and secondheader.h, and they both contained classes named CClass you''d get errors because you have 2 classes with the same name. You use namespaces to resolve the ambiguity. I don''t ever use them, though, and can''t really remember how they work.
Namespaces are to code, what directories are to a filesystem.
One of thier benefits is name-collision avoidance. They also let you package related classes, structs, enums, typedefs, and constants together.

I got a little carried away using namespace today:
  namespace MKH	{	namespace Network		{		namespace Socket			{			namespace Protocol				{				template<typename TAddress = IPAddress_v4>				struct RTP 					{					typedef TAddress Address;					};				}//namespace Protocol						template<class TProtocol>			class Listener				{				public:					bool Listen(const TProtocol::Address& bind)						{						//...						}				private:					TProtocol m_Protocol;				};			}//namespace Socket		}//namespace Network	}//namespace MKH  


  #include <MKH\Socket.hpp> //This brings the MKH::Network namespace into the local namespace.//We do this so we don't have to type MKH::Network::// in front of everything that needs it.using namespace MKH::Network;	typedef Socket::Protocols::RTP<> RTP;	Socket::Listener<CRTPTestDlg, RTP > m_rtpServer;	RTP::Address ip;		ip.dwAddress = 0x7f000000;	ip.port      = 1110;	m_rtpServer.Listen(ip);  


Magmai Kai Holmlor

"Oh, like you've never written buggy code" - Lee

"What I see is a system that _could do anything - but currently does nothing !" - Anonymous CEO

Edited by - Magmai Kai Holmlor on December 9, 2001 4:26:54 AM
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
From what I understood! Magmai you went over bord there

I think I would prefere to give my classes unique names.

Plus the fact that if in one cpp file you start using one name space you cant use the other one no? So you would still have to reference the other class with it''s name space??
You can just add stuff to the namespace from anywhere:

.h file #1
  namespace Bob{class George{};};  


.cpp file #1
  #include "file1.h" namespace Bob{George::George(){}}  


.h file #2
  namespace Bob{}  


.cpp #2
  namespace Bob{}  


And you can just keep adding files.

You can add stuff to the std namespace (or any other) if you really wanted to.

Magmai Kai Holmlor

"Oh, like you''ve never written buggy code" - Lee

"What I see is a system that _could do anything - but currently does nothing !" - Anonymous CEO
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
A namespace just takes the place of putting a prefix on a class name to make the name unique. It would be excessive if you actually had to specify the namespace. You only have to specify a namespace to resolve a conflict. So as an example you could have:

  //fileanamespace CompanyName{   namespace SystemA   {      namespace ProjectA      {         namespace LibraryA         {            class SomeClass;         };      };   };};//filebnamespace CompanyName{   namespace SystemA   {      namespace ProjectA      {         namespace LibraryB         {            class SomeClass;         };      };   };};//filecnamespace CompanyName{   namespace SystemA   {      namespace ProjectB      {         namespace LibraryA         {            class SomeClass;         };      };   };};//filednamespace CompanyName{   namespace SystemA   {      namespace ProjectC      {         namespace LibraryC         {            class SomeClass;         };      };   };};  


The fully qualified name of SomeClass in filea is CompanyName::SystemA:rojectA::LibraryA::SomeClass. Very cumbersome, but if there is no conflict you can just refer to it as SomeClass in your code. If you also use fileb in the same program then you have to use LibraryA::SomeClass and LibraryB::SomeClass to specify which one you want. If you also include filec then you need ProjectA::LibraryA::SomeClass, ProjectA::LibraryB::SomeClass or ProjectB::SomeClass. If you include filed as well then you add LibraryC::SomeClass or ProjectC::SomeClass, whichever you prefer. All you have to do is say you are using the namespace and any unresolved name is searched for in that namespace.

One nice thing about namespaces is that the first definition defines it, but subsequent ones extend it. That is differant than how a class behaves. If you did that with a class then you would get a compiler error saying duplicate name. In the example above the namespace CompanyName::SystemA includes all four classes if you include all four files. That lets you do things like set standards that the top namespace for all source developed in house be the company name. The indentation can get nasty. It would be nice if you could fully qualify a namespace and have the compiler generate the intermediate namespaces. Personally I just skip the indentation since I put everything in a single file in a single namespace.

You could get carried away and have a base class of Protocol::Listener and derived classes of IP::Listener. It isn''t really getting carried away as much as it is just a style. It made no differance if you called it IPListener or IP::Listener. One person might complain about typing two more letters while another complains that the parts of the name running together. Either way you had to take a specific action to avoid a name conflict that is basically a fundamental part of the program, i.e. you need to support multiple protocols. I would argue that is a specialize situation and that namespaces are more generally useful. You don''t need an anticipated conflict in names to justify using namespaces.
Keys to success: Ability, ambition and opportunity.
I will probably use them but not like crazy levels like you guys define there... JAVA packages are way more cleaner then this
Well maybe both of us can learn something, do tell, how to Java packages work?

Magmai Kai Holmlor

"Oh, like you''ve never written buggy code" - Lee

"What I see is a system that _could do anything - but currently does nothing !" - Anonymous CEO
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Java packages works exactly how you explained namespaces to me, exactly like a folder system. I sorta new what namespaces where just wasnt exactly sure how I would want to use them...

Say you have the following java source files...

    // One sourcepackage Engine.Modelclass Object{}// Another sourcepackage Engine.GUIclass Object{}// Another sourcepackage Engine// Tell java what packages to use.import Engine.Model.*; // Tell java to use all classes within the specified packageimport Engine.GUI.Object; // Tell java to use the specific objectclass MyEngine{   // Refers to the GUI object   Object myWindow = new Object();   Engine.Model.Object myMesh = new Engine.Model.Object();}    

You literaly have to have the physical folders
Engine
|
|-- MyEngine.java
|
|-- Model
| |
| |--- Object.java
| |
|-- GUI
| |
| |--- Object.java
| |

Now I have never fallen into a situation where 2 packages might have the same classes within, but I would assume you have to reference teh object by the exacte package... I will test it and see what happens.



Edited by - ANSI2000 on December 11, 2001 12:42:53 PM
quote:Original post by ANSI2000
Now I have never fallen into a situation where 2 packages might have the same classes within, but I would assume you have to reference teh object by the exacte package... I will test it and see what happens.


You're assumption is correct. The only real difference between Java packages and C++ namespaces is that in Java, source files are defined in a package (and thus all the classes defined in that source file are members of that package), whereas in C++ you can mix-and-match namespaces inside a single file. Besides that the differences are just syntax.

I also like Java's package protection, where classes, functions, or members are only visible to other entities inside the same package. Good way to get away from the friend keyword.

Does C++ have any sort of similar namespace protection?

"So crucify the ego, before it's far too late. To leave behind this place so negative and blind and cynical, and you will come to find that we are all one mind. Capable of all that's imagined and all conceivable."
- Tool
------------------------------


Edited by - wayfarerx on December 11, 2001 12:58:09 PM
"There is no reason good should not triumph at least as often as evil. The triumph of anything is a matter of organization. If there are such things as angels, I hope that they're organized along the lines of the mafia." -Kurt Vonnegut

This topic is closed to new replies.

Advertisement