Sireiz
Sireiz

Reputation: 393

C++ Namespaces and header files

I have seen codes with using namespace std;. Does it mean that if we use this then we don't have to include header files in the code or if we don't use namespaces, does it mean that we have to use std:: before every function, class?

Upvotes: 6

Views: 3382

Answers (3)

Aswin Murugesh
Aswin Murugesh

Reputation: 11080

You have to include header files and use namespaces.

The namespaces are contained in the header files, io streams like cin,cout are contained in the namespaces.So, only if you include the header file, namespace can be used. Without using namespace std, You have to use scope resolution operator every time you use those functions.

Upvotes: 7

ha9u63a7
ha9u63a7

Reputation: 6854

 using namespace std;

Is not really an ideal practice I would apply in a professional code base. The reason is that it practically "opens up" std namespace (packages in Java if you like) where you are probably doing "Hello world"ish programming i.e. not so severe as RT Embedded, Mission Critical, or Safety Critical. For example, I work in Interservice/Industry Training and Simulation where things are often safety/mission critical; people will propbably have a quiet word with me if I was using multiple namespaces so openly. It's not really about the size of your program, it is more about Good practice. Yes, if you have so many things to use from std namespace, then probably you can simply use it. A compromise, and also what I sometimes do, is:

using std::endl;
using std::string;
using std::cout;
using std::cin;
// And something like that

This "exposes" the ones that you will need for this scope and still lets you use:

string myStr;
cout << "Some cout" << endl;

Like what you mentioned in your question. Why not try that?

A "Good bit" of all is that if you follow the approach I mentioned, it also "Upgrade" your level of knowlege in C++ namespaces and possible STLs.

I know some people will say "Well that is stil hard work" but to me it is a good compromise, up to a point. :)

DON'T FORGET TO ADD THE NECESSARY HEADER FILES PLEASE :-)

Upvotes: 1

nullptr
nullptr

Reputation: 11058

using namespace std; means that all names from std namespace can be used without specifying their namespace explicitly (with std:: prefix). That is, after using namespace std;, both string and std::string are valid. Without using namespace std;, only std::string would work.

Header files still must be included.

Note that usage of using namespace is often discouraged as it populates your code with all names from that namespace, and conflicts may occur.

Upvotes: 1

Related Questions