Namespace clash in a nushell



By itself, it is very simple to understand a namespace clash. I’m by no means an expert C++ programmer so I can’t give a real world example of it, but I’m a proficient C# programmer and I’ve run into similar “context problems” with namespaces (C# has those as well). With that out of the way, here’s how I understand it.

Let’s say that you have a phone number directory. And you want to call your good friend Karen. Since Karen’s name is quite common, you also have a cousin called like that. Since you’re a fancy guy/girl and you LOVE to make simple and trivial stuff very complex, you write your own C++ program to call your friend Karen. The program just expects you to input her name, and then the program will make the call for you.

Then, you notice something… Your Software has no idea who you want to call! So it does what all software does and it crashes. Thing is, you, as the coding ninja you are, re-write your program and add an option to also write the last name of the person you want to call, if your program happens to not know which person to call when two similar names clash.

Now, when you call “Karen”, you can tell the program: I want to call Karen Williams, for example, which is the name of your friend. And, if you want to call your cousin, you instead tell the program to call Karen Miller.

Namespaces in C++ are just like that. Instead of Karen, let’s say that you have a handmade function called SquareRoot(), and since you’re very proud of your function, you store it in a C++ library you want to use in multiple programs and use the namespace of “MyAwesomeNamespace”.

So every time you want to use YOUR SquareRoot() function, you call it by MyAwesomeNameSpace::SquareRoot(someNumber);, with that syntax, you tell the C++ compiler that you want to use the SquareRoot() method from YOUR namespace, and therefore, the compiler will search between your functions in your namespace, and use the code of it, instead of the code from that shady third-party namespace you got from the Deep Web which also have by coincidence a function called SquareRoot.