Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'using' and 'using namespace'

Tags:

In the boost libraries, there are often examples of including the library like:

#pragma once #include <boost/property_tree/ptree.hpp> using boost::property_tree::ptree; 

Throughout my program I have been importing namespaces like this:

#include "../MyClass.h" using namespace MyClassNamespace; 

Can someone please explain:

  1. The difference between using and using namespace;
  2. What the advantage of negating the use of using namespace in favour of using;
  3. The differences in forward declaring using and using namespace;

Thanks

like image 591
Ospho Avatar asked Jul 28 '14 23:07

Ospho


People also ask

What is the difference between using and namespace C#?

The using directive is used to use a namespace in your code, without explicitly referencing to a namespace. This is of course useful when using a namespace more than once in a class. The directive does not change the state or status of the class, as the namespace statement does.

Why do we use using namespace?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

Should you use using namespace C++?

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. Example 1: CPP.

What is the difference between using and include in C++?

Simply put #include tells the pre-compiler to simply copy and paste contents of the header file being included to the current translation unit. It is evaluated by the pre-compiler. While using directive directs the compiler to bring the symbol names from another scope in to current scope.


1 Answers

using namespace makes visible all the names of the namespace, instead stating using on a specific object of the namespace makes only that object visible.

like image 71
George Kourtis Avatar answered Sep 19 '22 08:09

George Kourtis