C++ tip 2: Avoid using: "using namespace std"

During the initial phase of the game engine development I had the tendency of using:

using namespace std;

The using-directive makes methods from the std namespace available throughout your program. So for example, instead of writing the following:

std::vector<int> myNumber;

You can  write it as:

vector<int> myNumber;

This made it nice since I didn't have to specify std:: every time I wanted to use an operation from the library.

How to use namespace (1).jpg

It turns out that employing the using namespace std in your application is not a good idea at all. Instead, you should reference the namespace  as shown below:

std::cout<<"hello there"<<std::endl;
std::string myName="harold";
std::vector<float> myFloat=1.3;

void calculate(std::vector<float> uV);

I know writing std:: is tedious, but you need to get over it and start referencing the namespace.   Namespaces organize larger program components, such as in a game engine. For example, Let's say that your application uses the namespace MyEngine. Your classes definition and declaration should look like shown below:  

//In header file
namespace MyEngine{
  class Point{
  //…
  void coordinates();
  }
}

//In implementation file
namespace MyEngine{
    void Point::coordinates(){
    //…
    }
}

//so if you want to call the class, reference its namespace
void main(){
    MyEngine::Point* myPoint=new Point();
    myPoint->coordinates();
}

Doing so will prevent any clashes with any other library that could be using the same names.

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.