EmSAT Achieve Exam  >  EmSAT Achieve Notes  >  C++ for EmSAT Achieve  >  Namespace in C++

Namespace in C++ | C++ for EmSAT Achieve PDF Download

Introduction

Namespace provide the space where we can define or declare identifier i.e. variable,  method, classes. Using namespace, you can define the space or context in which identifiers are defined i.e. variable, method, classes. In essence, a namespace defines a scope.

Advantage of Namespace to avoid name collision

  • Namespaces are used in programming languages like C++ to avoid naming conflicts between different functions, classes, or variables that have the same name but different functionality. For instance, you may be developing a code that contains a function named 'xyz()', while another library may also have the same function 'xyz()'. This creates confusion for the compiler as it cannot differentiate which version of 'xyz()' function is being referred to in your code.
  • To avoid such naming conflicts, namespaces are used as an additional piece of information that uniquely identifies similar functions, classes, or variables available in different libraries. The namespace scope is designed to overcome this difficulty. A good example of namespace scope is the C++ standard library (std) that declares all the classes, methods, and templates. When we write a C++ program, we usually include the directive 'using namespace std;' to avoid any naming conflicts and allow the compiler to identify which function, class, or variable to use based on its namespace.
  • Using namespaces can greatly improve code readability, reduce the chances of naming conflicts, and simplify the maintenance and extension of large codebases. Therefore, it is considered a good practice to use namespaces in programming languages that support them.

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the namespace name as follows:

namespace  namespace_name 

{

    // code declarations i.e. variable  (int a;)

    method (void add();)

    classes ( class student{};)

}

  • It is to be noted that, there is no semicolon (;) after the closing brace.
  • To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:
  • namespace_name: :code;  // code could be variable , function or class.

The using directive

  • You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. 
  • The namespace is thus implied for the following code:

#include <iostream>

using namespace std;

// define first namespace

namespace first_ns

{

void func()

{

cout << "This is from first namespace" << endl;

}

}

// define second namespace

namespace second_ns

{

void func()

{

cout << "This is from second namespace" << endl;

}

}

//using first namespace by default

using namespace first_ns;

int main ()

{

//calls function from first namespace

func();


return 0;

}

  • The given code demonstrates how to use namespaces in C++. Namespaces are used to avoid name collisions that can occur when two or more libraries or modules use the same name for a function, class, or variable.
  • In the code, there are two namespaces defined - first_ns and second_ns. Both namespaces contain a function called func(). The code also includes a "using" directive, which tells the compiler to use the first namespace by default.
  • In the main function, the func() from the first namespace is called. The output will be "This is from first namespace", since the first namespace is being used by default.
  • By using namespaces, we can avoid name collisions and organize our code in a logical manner. This makes it easier to read, write, and maintain code, especially when working on larger projects.

Output

Inside first_space

  • Names introduced in a using directive obey normal scope rules. The name is visible from the point of the using directive to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.

Nested Namespaces

Namespaces can be nested where you can define one namespace inside another name space as follows:

SYNTAX:

    namespace namespace_name1 

    {

          // code declarations

          namespace namespace_name2 

          {

             // code declarations

          }

    }

You can access members of nested namespace by using resolution operators as follows:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace_name1
using namespace namespace_name1;
In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows:

#include <iostream>

using namespace std;


// first namespace

namespace first

{

  void func()

  {

     cout << "Inside first namespace" << endl;

  }


  // second namespace nested inside first

  namespace second

  {

     void func()

     {

        cout << "Inside second namespace" << endl;

     }

  }

}


// using directive to access nested namespace

using namespace first::second;


int main()

{

    // This calls the function from the second namespace

    func();

   

    return 0;

}

  • In this code, two namespaces are defined: first and second. The second namespace is nested inside the first namespace. Each namespace has a function named func(), which simply outputs a message to the console indicating which namespace it is in.
  • To access the func() function from the second namespace, a using directive is used to indicate that we want to use the second namespace nested inside the first namespace. This allows us to call the func() function without specifying the namespace it belongs to.
  • When the code is executed, it outputs the message "Inside second namespace" to the console, indicating that the func() function from the second namespace was called.

Output

Inside second_space

How namespace scope the entities including variable and functions:

#include <iostream>

using namespace std;

// First namespace

namespace first_ns {

  void func() {

    cout << "Inside first namespace" << endl;

  }

}

// Second namespace

namespace second_ns {

  void func() {

    cout << "Inside second namespace" << endl;

  }

}

int main() {

  // Calls function from first namespace

  first_ns::func();

  // Calls function from second namespace

  second_ns::func();

  return 0;

}

Output

Inside first_space

Inside second_space

  • This code demonstrates the use of namespaces in C++ to avoid name collisions between functions with the same name. The code defines two namespaces named first_ns and second_ns. Each namespace contains a function named func() that prints a message to the console.
  • In the main() function, we call the func() function from the first_ns namespace using the scope resolution operator :: as first_ns::func(). Similarly, we call the func() function from the second_ns namespace as second_ns::func().
  • By using namespaces, we can avoid naming conflicts between functions with the same name. When we have two functions with the same name in different namespaces, we can specify which function to call by using the namespace name followed by the scope resolution operator and the function name.

Consider the following C++ program

// A program to demonstrate need of namespace

int main()

{

    int value;

    value = 0;

    double value; // Error here

    value = 0.0;

}

Output

Compiler Error:
'value' has a previous declaration as 'int value'
In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope. Using namespaces, we can create two variables or member functions having the same name.

#include <iostream>

using namespace std; 

// Variable created inside namespace

namespace first {

int val = 500;

// Global variable

int val = 100; 

int main()

{

    // Local variable

    int val = 200; 

    // These variables can be accessed from

    // outside the namespace using the scope

    // operator ::

    cout << first::val << '\n'; 

    return 0;

}

The output of this code is '500'. This is because we are accessing the val variable inside the first namespace using the scope resolution operator '::'. This allows us to differentiate between variables with the same name declared in different scopes or namespaces. In this case, the val inside the first namespace has a value of 500, while the global val has a value of 100 and the local val inside the main function has a value of 200.

Output

500

Definition and Creation: Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names. Namespaces provide the space where we can define or declare identifiers i.e. names of variables, methods, classes, etc.

  • A namespace is a feature added in C++ and is not present in C.
  • A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it.
  • Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.

A namespace definition begins with the keyword namespace followed by the namespace name as follows:

namespace namespace_name 

{

   int x, y; // code declarations where 

             // x and y are declared in 

             // namespace_name's scope

}

  • Namespace declarations appear only at global scope.
  • Namespace declarations can be nested within another namespace.
  • Namespace declarations don’t have access specifiers (Public or Private).
  • No need to give a semicolon after the closing brace of the definition of namespace.
  • We can split the definition of namespace over several units.

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the namespace name as follows:

namespace  namespace_name{

     // code declarations i.e. variable  (int a;)

     method (void add();)

     classes ( class student{};)

}

It is to be noted that there is no semicolon (;) after the closing brace.
To call the namespace-enabled version of either a function or a variable, prepend the namespace name as follows:
namespace_name: :code;  // code could be a variable, function or class.

#include <iostream>

using namespace std;

// namespace for mathematical operations

namespace math_ops

{

int add(int a, int b)

{

return a + b;

}

int multiply(int a, int b)

{

return a * b;

}

}

// namespace for string operations

namespace string_ops

{

string concat(string s1, string s2)

{

return s1 + s2;

}

int length(string s)

{

return s.length();

}

}

int main ()

{

// Using math_ops namespace

int sum = math_ops::add(5, 6);

int product = math_ops::multiply(3, 4);

cout << "Sum: " << sum << endl;

cout << "Product: " << product << endl;

// Using string_ops namespace

string s1 = "Hello";

string s2 = "World";

string s3 = string_ops::concat(s1, s2);

int s3_length = string_ops::length(s3);

cout << "Concatenated string: " << s3 << endl;

cout << "Length of the string: " << s3_length << endl;

return 0;

}

Output

// Sum: 11

// Product: 12

// Concatenated string: HelloWorld

// Length of the string: 10

  • This program demonstrates how to use namespaces in C++ to group related entities such as variables, functions, classes, etc. into a named scope. In this program, we define two namespaces named "math_ops" and "string_ops".
  • The "math_ops" namespace contains two functions named "add" and "multiply" to perform addition and multiplication operations on integers. The "string_ops" namespace contains two functions named "concat" and "length" to concatenate strings and find the length of a string, respectively.
  • In the main function, we access the functions from both namespaces using the namespace qualifier "::". We call the "add" and "multiply" functions from the "math_ops" namespace and the "concat" and "length" functions from the "string_ops" namespace.
  • When we run the program, it displays the results of the mathematical operations and the concatenated string along with its length on the console. The output shows that the functions from both namespaces are accessed separately without any naming conflicts.

The using directive

You can avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code:

#include <iostream>

using namespace std;

// namespace for mathematical operations

namespace math_ops

{

int add(int a, int b)

{

return a + b;

}

int subtract(int a, int b)

{

return a - b;

}

}

// namespace for string operations

namespace string_ops

{

string concat(string s1, string s2)

{

return s1 + s2;

}

int length(string s)

{

return s.length();

}

}

using namespace math_ops;

int main ()

{

// This calls the add function from math_ops namespace.

int sum = add(5, 6);

cout << "Sum: " << sum << endl;

// This calls the subtract function from math_ops namespace.

int difference = subtract(10, 4);

cout << "Difference: " << difference << endl;

return 0;

}

  • This program demonstrates how to use the "using" keyword with namespaces in C++ to selectively bring the identifiers of a namespace into the current scope. In this program, we have two namespaces named "math_ops" and "string_ops".
  • The "math_ops" namespace contains two functions named "add" and "subtract" to perform addition and subtraction operations on integers. The "string_ops" namespace contains two functions named "concat" and "length" to concatenate strings and find the length of a string, respectively.
  • In the main function, we use the "using" keyword to bring all the identifiers from the "math_ops" namespace into the current scope. This allows us to call the "add" and "subtract" functions directly without using the namespace qualifier "::".
  • When we run the program, it displays the results of the mathematical operations on the console. The output shows that the "using" keyword can be used to simplify the code and reduce the typing effort.

Output

Inside first_space

Instead of accessing the whole namespace, another option (known as using declaration) is to access a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows:
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows:

#include <iostream>

using std::cout;

int main ()

{

// Here we use "std::endl" with "std" namespace to output a message on the console.

cout << "std::endl is used with std!" << std::endl;

return 0;

}

Output

std::endl is used with std!

  • This program demonstrates how to use namespaces in C++ to avoid namespace conflicts. In C++, namespaces are used to group related identifiers (such as variables, functions, and classes) together and avoid naming conflicts between them.
  • In this program, we include the "iostream" header file which contains the standard input/output stream objects and the "std" namespace. The "using" keyword is used to bring only the "cout" identifier from the "std" namespace into the current scope.
  • In the main function, we use the "cout" object to output a message on the console. We also use "std::endl" with "std" namespace to insert a newline character and flush the output buffer. This ensures that the message is immediately displayed on the console.
  • When we run the program, it displays the output message "std::endl is used with std!" on the console. This demonstrates how to use namespaces in C++ to avoid naming conflicts and use the identifiers from the correct namespace.

Names introduced in a using directive obey normal scope rules, i.e., they are visible from the point the using directive occurs to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.

#include <iostream>

using namespace std;

namespace ns1 {

int value() {

return 5;

}

} // namespace ns1

namespace ns2 {

const double x = 100;

double value() {

return 2 * x;

}

} // namespace ns2

int main()

{

// Access value function within ns1

cout << ns1::value() << '\n';

// Access value function within ns2

cout << ns2::value() << '\n';

// Access variable x directly

cout << ns2::x << '\n';

return 0;

}

Output

5
200
100

Classes and Namespace

The following is a simple way to create classes in a namespace: 

#include <iostream>

using namespace std;

namespace custom

{

// A class defined inside the custom namespace

class Person

{

public:

void introduce()

{

cout << "custom::Person::introduce()" << endl;

}

};

}

int main()

{

// Creating an object of Person class

custom::Person p;

// Invoking the introduce() method of Person class

p.introduce();

return 0;

}

Output

custom::Person::introduce()

  • This is a simple C++ program that demonstrates the use of a class inside a namespace. A namespace is a way to group related variables, functions, and classes. In this program, a namespace named "custom" is defined, which contains a class named "Person" with a single method named "introduce". 
  • The main() function creates an object of the Person class using the namespace scope resolution operator "::", and invokes the introduce() method of the object. 
  • Finally, the output "custom::Person::introduce()" is displayed on the console.

 A class can also be declared inside namespace and defined outside namespace using the following syntax: 

#include <iostream>

using namespace std;

namespace custom {

// Forward declaration of the class geek inside the custom namespace

class geek;

} // namespace custom

// Definition of the geek class outside the custom namespace

class custom::geek {

public:

void printMessage() { cout << "custom::geek::printMessage()\n"; }

};

int main()

{

// Creating an object of the geek class

custom::geek obj;

// Invoking the printMessage() method of the geek class

obj.printMessage();

return 0;

}

Output

custom::geek::printMessage()

  • This is a C++ program that demonstrates the use of a class inside a namespace. The namespace named "custom" is defined with a forward declaration of the "geek" class. 
  • The actual definition of the "geek" class is done outside the namespace using the namespace scope resolution operator "::". The main() function creates an object of the "geek" class using the namespace scope resolution operator "::", and invokes the printMessage() method of the object. 
  • Finally, the output "custom::geek::printMessage()" is displayed on the console. This approach is used when the class definition is needed to be done outside the namespace and yet we want to define the class as a member of the namespace.

We can define methods as well outside the namespace. The following is an example code: 

#include <iostream>

using namespace std;

// Creating a namespace

namespace myns {

void show();

class student {

public:

void show();

};

} // namespace myns

// Defining methods of namespace

void myns::student::show() {

cout << "myns::student::show()\n";

}

void myns::show() {

cout << "myns::show()\n";

}

// Driver code

int main() {

myns::student obj;

myns::show();

obj.show();

return 0;

}

Output

// myns::show()

// myns::student::show()

  • This C++ program demonstrates that we can define methods outside the namespace. Firstly, a namespace named "myns" is created, which contains two functions, one is a simple function named "show()" and the other is a class named "student" which contains a function named "show()".
  • After defining the namespace, the methods of the namespace are defined outside the namespace. These methods are defined using the namespace and scope resolution operator "::".
  • In the main function, an object of the "student" class is created and the "show()" methods of the namespace and the object are called. The output of the program is the string "myns::show()" followed by "myns::student::show()" which is printed on the console.

Nested Namespaces

Namespaces can be nested, i.e., you can define one namespace inside another namespace as follows:

namespace namespace_name1 {

  // code declarations

  namespace namespace_name2 {

     // code declarations

  }

}

You can access the members of a nested namespace by using the resolution operator (::) as follows:

// to access members of namespace_name2

using namespace namespace_name1::namespace_name2;

// to access members of namespace:name1

using namespace namespace_name1;

In the above statements, if you are using namespace_name1, then it will make the elements of namespace_name2 available in the scope as follows:

#include <iostream>

using namespace std;

// Define a namespace named "animal"

namespace animal {

// Define a namespace named "mammal" inside the namespace "animal"

namespace mammal {

void sound() {

cout << "Mammals produce sounds.\n";

}

}

}

// Using directive to access the "mammal" namespace inside "animal" namespace

using namespace animal::mammal;

// Driver code

int main () {

// This calls function from "mammal" namespace inside "animal" namespace.

sound();

return 0;

}

Output

Mammals produce sounds.

  • This C++ program demonstrates nested namespaces and using directive. A namespace named "animal" is defined, which contains a namespace named "mammal". Inside the "mammal" namespace, a function named "sound()" is defined which outputs the string "Mammals produce sounds.".
  • Using the using directive "using namespace animal::mammal;", the "mammal" namespace inside "animal" is accessed, and the "sound()" function is called without specifying the namespace.
  • In the main function, the "sound()" function from the "mammal" namespace inside "animal" namespace is called. The output of the program is the string "Mammals produce sounds." which is printed on the console.

Namespace provides the advantage of avoiding name collision

For example, you might be writing some code that has a function called xyz() and there is another library available in your code which also has the same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.

  • A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables, etc. with the same name available in different libraries. 
  • The best example of namespace scope is the C++ standard library (std), where all the classes, methods and templates are declared. Hence, while writing a C++ program, we usually include the directive using namespace std;
The document Namespace in C++ | C++ for EmSAT Achieve is a part of the EmSAT Achieve Course C++ for EmSAT Achieve.
All you need of EmSAT Achieve at this link: EmSAT Achieve
70 videos|45 docs|15 tests

Top Courses for EmSAT Achieve

70 videos|45 docs|15 tests
Download as PDF
Explore Courses for EmSAT Achieve exam

Top Courses for EmSAT Achieve

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

mock tests for examination

,

pdf

,

ppt

,

Viva Questions

,

Important questions

,

past year papers

,

Previous Year Questions with Solutions

,

Namespace in C++ | C++ for EmSAT Achieve

,

MCQs

,

Namespace in C++ | C++ for EmSAT Achieve

,

practice quizzes

,

Exam

,

shortcuts and tricks

,

Sample Paper

,

study material

,

Semester Notes

,

Namespace in C++ | C++ for EmSAT Achieve

,

Extra Questions

,

Summary

,

Objective type Questions

,

video lectures

,

Free

;