3

Agree that using namespace XXX is not a good practice. However, prefixing namespaces:: in each and every call is not only tedious but sometimes irritating too. for example, look at the code below which is using standard namespace std

#include <iostream>

int main()
{
    std::cout << "Hello World" << std::endl;
    return 0;
}

However, I can get rid of repeating std:: by just importing the function itself via using keyword as

#include <iostream>
using std::cout;
using std::endl;
int main()
{
    cout << "Hello World" << endl;
    return 0;
}

Is there any specific reason why I shouldn't do this rather than prefixing std:: in all the statements. if there is no specific reason, why this approach is not promoted as against prefixing std::?

I understand from C++ specification that using std::func will also import overloaded definition.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Daksh Gupta
  • 7,554
  • 2
  • 25
  • 36

2 Answers2

4

The main reason for using namespace qualification is that it avoids name collision, like a local name distance colliding with std::distance.

The main reason for avoiding qualification is that the code is then shorter, and to some programmers (including me) then appears more clear because it just reads as English.

The problem with name collisions increases with the size of the code, and so that's one criterion: the shorter the code, the less does it make sense to add overhead to avoid name collisions. And vice versa, the larger the code base is, and the longer it takes to build, the more reason is there to avoid name collisions.

One main rule:

Do not ever add a blanket using namespace... in the global namespace in a header file.

But apart from that it's a so called engineering decision: go with your gut feeling about advantages and costs and ugliness and readability and clarity, and so on.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

Whether you use

using namespace std;

or

using namespace std::cout;
using namespace std::end;

does not matter much if it is in a .cpp file. Any name conflicts that arise from those can be fixed locally.

The opposition to their usage is very strong when it comes to header files.

I wouldn't worry too much about either approach in a .cpp file

R Sahu
  • 204,454
  • 14
  • 159
  • 270