Skip to main content

C++ Namespaces

C++ namespace are used to define a scope or uniqueness of scope. Or we can say namespace are resolve the ambiguity of the access of scops. Let see the example to understand this point.

#include<iostream>
int main(){
  
  int auxiliary=10;

  float auxiliary=90.34; //error in this line
}
Error like this: previous declaration as 'int auxiliary'

In this program there are two auxiliary variables in same scope so compiler was produced an error. We can easily to solve this problem using provide and new name of (float auxiliary). But assume that this variables are exist in predefined header files. And we are not applied to changes this variable names. So we are use c++ namespace features and solve this problem very accurate manner. So consider this program.

Program
#include<iostream>
//define the namespace solve ambiguity of same variable name
namespace floatVar{
  float auxiliary=90.34f;
};
namespace intVar{
  int auxiliary=10;
};

int main(){
  std::cout<<"floatVar(auxiliary) :" <<floatVar::auxiliary<<std::endl;
  std::cout<<"intVar  (auxiliary) :" <<intVar::auxiliary;
}
Output
floatVar(auxiliary) :90.34
intVar  (auxiliary) :10

Observe this program we are defined the two namespace floatVar and intVar. And defined the auxilary variable inside this. Access namespace variable using following syntax.

namspace_name :: variable_name

Namespace name is user defined name we are use namespace variable using scope resolution operator.

Understand following points

1) std is also a namespace there are defined of iostream header file. Find iostream file where install your c compiler. Here given iostream header file code you can see that here defined std namespace.

// Standard iostream objects -*- C++ -*-

// Copyright (C) 1997-2018 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

/** @file include/iostream
 *  This is a Standard C++ Library header.
 */

//
// ISO C++ 14882: 27.3  Standard iostream objects
//

#ifndef _GLIBCXX_IOSTREAM
#define _GLIBCXX_IOSTREAM 1

#pragma GCC system_header

#include <bits/c++config.h>
#include <ostream>
#include <istream>

namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

  /**
   *  @name Standard Stream Objects
   *
   *  The &)/lt;iostream&)/gt; header declares the eight <em>standard stream
   *  objects</em>.  For other declarations, see
   *  http://gcc.gnu.org/onlinedocs/libstdc++/manual/io.html
   *  and the @link iosfwd I/O forward declarations @endlink
   *
   *  They are required by default to cooperate with the global C
   *  library's @c FILE streams, and to be available during program
   *  startup and termination. For more information, see the section of the
   *  manual linked to above.
  */
  //@{
  extern istream cin;   /// Linked to standard input
  extern ostream cout;    /// Linked to standard output
  extern ostream cerr;    /// Linked to standard error (unbuffered)
  extern ostream clog;    /// Linked to standard error (buffered)

#ifdef _GLIBCXX_USE_WCHAR_T
  extern wistream wcin;   /// Linked to standard input
  extern wostream wcout;  /// Linked to standard output
  extern wostream wcerr;  /// Linked to standard error (unbuffered)
  extern wostream wclog;  /// Linked to standard error (buffered)
#endif
  //@}

  // For construction of filebuffers for cout, cin, cerr, clog et. al.
  static ios_base::Init __ioinit;

_GLIBCXX_END_NAMESPACE_VERSION
} // namespace

#endif /* _GLIBCXX_IOSTREAM */

std namespace is contain lot of external variables (like cin,cout and so on). Use this variable by using this name space std. Next section we are discussed about everything in std namespace, like how to append on variable inside a std namespace. But view the example to utilize std namespace.

#include<iostream>
//use of std namespace in our program
using namespace std;
int main(){
   //replace std before cout
   cout<<"Learen about C++ namespace";
   return 0;
}
Output
Learen about C++ namespace

note that std::cout<<"message"; are used to if when not include std namespace in our program. When we are include that namespace then no need to use (std:: ).

2) c++ are allowing to utilize same name of variable within multiple namespace.

#include<iostream>
using namespace std;
/*Defined Collage Namespace*/
namespace Employee{
  int age=25;
}
namespace Student{
  int age=21;
}
int main(){
  
  //display age of employee
  cout<<"Employee Age :"<<Employee::age<<endl;
  cout<<"Student Age  :"<<Student::age;
  return 0;
  //end of execution of program 
}
Output
Employee Age :25
Student Age  :21

3) start the scope of namespace are where it is used. see the example.

#include<iostream>

/*Defined Employee Namespace*/
namespace Employee{

    void display(){
    cout<<"Employee display function";
  }

}

//include std namespace
using namespace std;
int main(){
  
  Employee::display();
  return 0;
  //end of execution of program 
}
Output
error: 'cout' was not declared in this scope
   cout<<"Employee display function";

Note that std namespace are after Employee namespace so we are not capable to utilized std namespace directly inside Employee. So conclusion is predefined namespace are included in just after the header file. Make sure cleare this point.

#include<iostream>

//include std namespace
using namespace std;
/*Defined Employee Namespace*/

namespace Employee{

    void display(){
    cout<<"Employee display function";
  }

}

int main(){
  
  Employee::display();
  return 0;
  //end of execution of program 
}
Output
Employee display function

User defined Namespace

C++ are allowed to make on user defined namespace.inside a namespace we are defined variables and functions. See the syntax.

namespace namespace_name{
  //defined function and veriable here
};
Example
/* Example User defined Namespace
*/
#include<iostream>
//Perdefined namespace 
using namespace std;
//user defined namespace
namespace Book{
  void display(){
    cout<<"Book Display Function"<<endl;
  } 
};
namespace Employee{
  void display(){
    cout<<"Employee Display Function"<<endl;
  }
}
int main(){
  Book::display();
  Employee::display();
  return 0;
  
}
Book Display Function
Employee Display Function

Nested Namespaces

c++ allowing to declare and use of nested Namespace. There are special case when we need to utilize nested namespace. see syntax.

//namespace identify_name
  namespace outer_namespace{
  //defined function and variables
  namespace inner1{

    namespace most_inner{
       //code
    };

  };
  namespace inner2{
    //code
  };
};

Example
/*
  Nested NameSpace
*/

#include<iostream>
using namespace std;
/*Defined Collage Namespace*/
namespace Collage{
  /*
    Defined nested namespace Student
  */
  namespace Student{
    //Defined the function inside namespace student
    float percentage(int subject,float marks){
      //return the percentage of total marks
    return (marks/subject);
    }
  }
}
int main(){
  /*
  Access the Nested namespace by scope resolution operator
  */
  float percent=Collage::Student::percentage(6,510.3);
  cout<<"Percent Is :"<<percent;
  
  return 0;
  //end of execution of program 
}
Output
Percent Is :85.05

std namespace

std namespace is an standard namespace. This are exist in lot of c++ header files. And this area contains objects (cin,cout) and some standard variable like( endl). So need to using of those variables and object then required this namespace. In previous example there are demonstrates how to used this namespace in our program.

And here given example how to defined on variables and function within the std namespace. This are same as overloading of namespace. see an example.

/*
  Example of overload std namespace
*/
#include<iostream>
//overload namespace
namespace std{
  int auxilary=10; //variables
  //function of namespace
  int sum(int x,int y){
    return x+y;
  }
}
using namespace std;

int main(){
  //access direct namespace function
  cout<<"Sum is :"<<sum(3,4)<<endl;
  cout<<"auxilary :"<<auxilary;
 
  return 0; 
}
Output
Sum is :7
auxilary :10

Note that here given an example to how to overload std name space in our program. This is not a good programming practice to override this name by programmer. But internally most of header file are override this namespace.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment