Download

What is the purpose of "Using Namespace std"?

Hi, I was wondering what the purpose of “Using Namespace std;” means exactly.

Hi, this isn’t really anything to do with the unreal engine since it doesn’t use the standard library (to my knowledge). This kind of question is probably better off being asked in stack exchange or somewhere similar.

But what ‘using namespace X’ does is bring all names from namespace X into the current namespace, in this case the global namespace. It saves you from having to write things like std::vector<std:: pair<int, double>> which becomes really annoying after a while. This is fine for small programs which are almost exclusively using the standard library but for larger programs it can clutter the global namespace and lead to name conflicts.

It is a short cut in short. It saves you from having to write, in the current scope, the namespace of the class, primitive, etc.

So by using “using namespace std” you do not have to write


std::cout << "Hello World" << std::endl;

Namespaces were implemented in C++ to stop clashing of function/class names, e.g lets say Windows.h has a ‘Time’ class if I were to create another class named ‘Time’ then the compiler will spit out errors as numerous classes exist with the same name (ambiguity). I could wrap my time class in a namespace:


 namespace UE4Functions
{
   class Time
   {
   };

}

This way I could reference the Windows.h Time class normally and I could reference my new Time class through UE4Functions::Time (no longer ambiguous). Doing ‘using namespace UE4Functions’ means I don’t have to do UE4Functions::Time I could just do Time but this clashes with the Windows function again. This is why you should not use 'using ’ often or atleast scope it to a class or a function, i.e using std::cout instead of using std.


namespace Test
{
	class Testing
	{
	public:
		int a;
	};
}

class Testing
{
public:
	float b;
};

using namespace Test;

void main(void)
{
	Testing a; // Ambiguous
	Test::Testing b;
}

Thanks :slight_smile: Knowing that helps a lot!