Wait, did I mean the Paris that is in France, Europe, or Paris in Texas, USA? There would be name collision, if we would use mere 'Paris' without the encompassing namespace.
Names must be unique. We like names descriptive, but short. If we both name a thing 'fun' and they are totally unrelated, then John Doe cannot write a program that has both types of fun, ... unless they are in different namespaces that make unambiguous references possible.
They don't do much in 10 line programs (unless you re-use a name in the standard namespace or something). There are several things you will see people do that don't make sense or do much in short programs but are absolutely critical for large multi-developer projects spanning thousands (and even millions) of lines of code.
So you are not wrong, its about useless / pointless here.
Two programmers working on a game, one working on the combat code section and the other working on the exploration code.
Both create a Fire() function. 1st fires a crossbow, 2nd lights a torch. Without using separate namespaces the compiler would complain of clashing names for the Fire() functions.
Using namespaces it becomes easier to see which Fire() function is used. Use becomes self-documenting.
#include <iostream>
// stores all the combat functions, classes and variables
namespace Combat
{
void Fire()
{
std::cout << "Whoosh, you unleash a bolt from your crossbow.\n";
}
}
// stores all the exploration functions, classes and variables
namespace Exploration
{
void Fire()
{
std::cout << "You set your torch ablaze.\n";
}
}
int main()
{
Combat::Fire();
Exploration::Fire();
}
Whoosh, you unleash a bolt from your crossbow.
You set your torch ablaze.
I use namespaces in commonly reused objects/functions I code so I know I am using custom code.
+-------+
Now, regarding the common beginning programmer "using namespace std;" DON'T!
As your programs grow in size, when you start using dozens of custom/third party functions/objects in your programs the likelihood of using a name of some function/object in the std:: namespace becomes increasingly possible.
Always typing std:: when I use any C++ standard library object or function is now a habit, I do it without really thinking about it. A couple of extra characters and I don't have to worry about name conflicts.
Doing it also self-documents my code that I am using the C++ standard library.
So if we were to merge code in github and I had a function called doAthing() and you had a function called doAthing()
Giving them different namespaces allows the compiler to tell the two appart. That sounds useful, actually.
usingnamespace std; trashes the ability to keep similarly named classes/functions as separate. The C++ standard library is HUGE, it is all too easy to make name clashes happen.