devxlogo

A Using Declaration and a Using Directive

A Using Declaration and a Using Directive

A namespace is a scope in which declarations and definitions are grouped together. In order to refer to any of these from another scope, a full qualified name is required. However, repeating the full qualified name over and over again is tedious, error prone and less readable. Instead, a using declaration or a using directive can be used.

A using declaration is a sequence consisting of the keyword using followed by a namespace:: member. It instructs the compiler to locate every occurrence of a certain declaration (type, operator, function, etc.) in the specified namespace, as if the full qualified name were supplied:

 #include   //STL vector; belongs to namespace stdvoid main() {   using std::vector;  //using declaration; every occurrence of vector is looked up in std    vector  vi; //without a using declaration, a full qualified name: std::vector  would be required   //... }//end of main; the above using declaration goes out of scope here

A using directive instructs the compiler to recognize all members of a namespace and not just one. It consists of the following sequence: ‘using namespace’ followed by a namespace-name. For example:

 #include    //STL vector; belong to namespace std#include  //iostream classes and operators are also in namespace stdvoid main() {  using namespace std; //directive; all  and  declarations  now accessible    	  vector   vi;  vi.push_back(10);  cout

devx-admin

Share the Post: