The Wayback Machine - https://web.archive.org/web/20240905231803/https://www.geeksforgeeks.org/namespace-in-c-set-2-extending-namespace-and-unnamed-namespace/
Open In App

namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)

Last Updated : 28 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We have introduced namespaces in below set 1.
Namespace in C++ | Set 1 (Introduction)

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:

C++




#include <iostream>
using namespace std;
// first name space
namespace first_space
{
  void func()
  {
     cout << "Inside first_space" << endl;
  }
}
 
// second name space
namespace second_space
{
  void func()
  {
     cout << "Inside second_space" << endl;
  }
}
using namespace first_space;
int main ()
{
   // This calls function from first name space.
  func();
  return 0;
}


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:

C++




#include <iostream>
using namespace std;
 
// first name space
namespace first_space
{
  void func()
  {
     cout << "Inside first_space" << endl;
  }
  // second name space
  namespace second_space
  {
     void func()
     {
        cout << "Inside second_space" << endl;
     }
  }
}
using namespace first_space::second_space;
int main ()
{
    // This calls function from second name space.
      func();
   
      return 0;
}


It is also possible to create more than one namespaces in the global space. This can be done in two ways. 
 

  • namespaces having different names 
     

CPP




// A C++ program to show more than one namespaces
// with different names.
#include <iostream>
using namespace std;
 
// first name space
namespace first
{
   int func() {  return 5; }
}
 
// second name space
namespace second
{
   int func() { return 10; }
}
 
int main()
{
   // member function of namespace
   // accessed using scope resolution operator
   cout << first::func() <<"\n";       
   cout << second::func() <<"\n";
   return 0;
}


  • Output: 
     
5
10
  • Extending namespaces (Using same name twice) 
    It is also possible to create two namespace blocks having the same name. The second namespace block is nothing but actually the continuation of the first namespace. In simpler words, we can say that both the namespaces are not different but actually the same, which are being defined in parts. 
     

CPP




// C++ program to demonstrate namespace extension
#include <iostream>
using namespace std;
 
// first name space
namespace first
{
   int val1 = 500; 
}
 
// rest part of the first namespace
namespace  first
{
   int val2 = 501; 
}
 
int main()
{
   cout << first::val1 <<"\n";       
   cout << first::val2 <<"\n";
   return 0;
}


  • Output: 
     
500
501

Unnamed Namespaces 
 

  • They are directly usable in the same program and are used for declaring unique identifiers.
  • In unnamed namespaces, name of the namespace in not mentioned in the declaration of namespace.
  • The name of the namespace is uniquely generated by the compiler.
  • The unnamed namespaces you have created will only be accessible within the file you created it in.
  • Unnamed namespaces are the replacement for the static declaration of variables.

 

CPP




// C++ program to demonstrate working of unnamed
// namespaces
#include <iostream>
using namespace std;
 
// unnamed namespace declaration
namespace
{
   int rel = 300;
}
 
int main()
{
   cout << rel << "\n"; // prints 300
   return 0;
}


Output: 
 

300

 



Previous Article
Next Article

Similar Reads

Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
Namespace in C++ | Set 1 (Introduction) Namespace in C++ | Set 2 (Extending namespace and Unnamed namespace) Different ways to access namespace: In C++, there are two ways of accessing namespace variables and functions. Defining a Namespace: A namespace definition begins with the keyword namespace followed by the namespace name as follows: namespac
5 min read
Check whether the number has only first and last bits set | Set 2
Given a positive integer n, check whether only the first and last bits are set in the binary representation of n. Print 'Yes' or 'No'.Examples: Input: 9 Output: Yes (9)10 = (1001)2, only the first and last bits are set. Input: 15 Output: No (15)10 = (1111)2, except first and last there are other bits also which are set. We have already discussed a
4 min read
Print Binary Tree levels in sorted order | Set 2 (Using set)
Given a tree, print the level order traversal in sorted order. Examples : Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 7 5 6 1 2 3 4 Input : 7 / \ 16 1 / \ 4 13 Output : 7 1 16 4 13 We have discussed a priority queue based solution in below post.Print Binary Tree levels in sorted order | Set 1 (Using Priority Queue) In this post, a set (which is impl
5 min read
Frequent Item set in Data set (Association Rule Mining)
INTRODUCTION:Frequent item sets, also known as association rules, are a fundamental concept in association rule mining, which is a technique used in data mining to discover relationships between items in a dataset. The goal of association rule mining is to identify relationships between items in a dataset that occur frequently together.A frequent i
6 min read
Permutation and Combination | Set-2
Question 1: How many number greater than ten thousand can be formed from the digits 0, 1, 2, 3, 4 without repetition ? Solution : In order to form a number greater than 10000 we should have only 5 digits. Since, we have 5 digits we cannot take 0 in starting position. _ _ _ _ For first digit, we have 4 choices. For second digit, again we have 4 choi
5 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Data Structures and Algorithms | Set 36
Que - 1. The function shiftNode() which takes as input two linked lists- destination and source. It deletes front node from source and places it onto the front of destination. Choose the set of statements which replace X, Y, Z in given function. void shiftNode(struct node** destRoot, struct node** srcRoot) { // the front of source node struct node*
4 min read
Data Structures and Algorithms | Set 37
Que - 1. For 8 keys and 6 slots in a hashing table with uniform hashing and chaining, what is the expected number of items that hash to a particular location. (A) 2.33 (B) 0.75 (C) 1.33 (D) 2 Solution: Probability that key1 ends up in slot 1 = 1/6 Probability that key2 ends up in slot 1 = 1/6 Probability that key3 ends up in slot x = 1/6 Probabilit
4 min read
Segregate even and odd numbers | Set 2
Given an array of integers, segregate even and odd numbers in the array. All the even numbers should be present first, and then the odd numbers. Examples: Input : 1 9 5 3 2 6 7 11 Output : 6 2 3 5 7 9 11 1 Input : 1 3 2 4 7 6 9 10 Output : 10 2 6 4 7 9 3 1 We have discussed one approach in Segregate Even and Odd numbers. In this post, a different s
5 min read
Trigonometry &amp; Height and Distances | Set-2
Question 1: Find the maximum value of (2sinθ + 3 cosθ) Solution : Max value of (asinθ + bcosθ) = √(a2 + b2)) So, max value = √(22 + 32) = √(4 + 9) = √13 Question 2: Find the minimum value of the 4tan2θ + 9cot2θ Solution : Minimum value = √ab Here a = 4 and b = 9 Minimum value = √(4x9) = √36 = 6 Question 3: If θ be an acute angle and 7sin2θ + 3cos2θ
5 min read
Difference between RISC and CISC processor | Set 2
A microprocessor is a processing unit on a single chip. It is an integrated circuit that performs the core functions of a computer CPU. It is a multipurpose programmable silicon chip constructed using Metal Oxide Semiconductor (MOS) technology which is clock-driven and register-based. It accepts binary data as input and provides output after proces
4 min read
Ratio proportion and partnership | Set-2
Question 1: The ratio of the age of a man and his wife is 6:5. After 16 years, the ratio becomes 10:9. Find the husband’s age when the wife was born. Solution: Let x is husband’s age And y is the wife’s age. x/y= 6/5 x=(6/5)y After 16 years, (x + 16)/(y + 16) = 10/9 9x + 144 = 10y + 160 9*(6/5)y = `10y + 16 54y - 50y = 80 y=20 Then x = 24 When the
5 min read
Mixture and Alligation | Set 2
Question 1: 30 litres of a mixture of milk and water contains 10% of water, the water to be added, to make the water content 25% in the new mixture. Find how many litres water will be added? Solution : Water in the 30 litre of mixture = 30 x 10/100 = 3 litres Milk in the mixture = 30 - 3 = 27 litres Let x litres of water is mixed. Acc. to question
3 min read
Profit and loss | Set-2
Question 1: The cost price of 12 books is equal to the selling price of 10 books. The gain percent is : Solution : Given 12 CP = 10 SP CP/SP = 10/12 = 5/6 Profit = SP - CP =&gt; 6 - 5 = 1 Profit (%) = profit/CP x 100 =&gt; 1/5 x 100 =&gt; 20 % Question 2: If the loss% on article is 15%. Then the ratio of cost price and selling price will be Solutio
6 min read
How to Install and Set Up SAS University Edition
Statistical Analysis System (SAS) , one of the most powerful data analytical software in the market which has recently released a university edition of its software. Despite being proprietary software, the developers have decided to do so, to help the students learn the basics of SAS programming. This edition offers the user all the basic functiona
3 min read
Construct a tree from Inorder and Level order traversals | Set 2
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Following is an example to illustrate the problem. Examples: Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output: Construct the tree represented by the
15+ min read
JP Morgan Chase and Co Interview Experience | Set 1 (For Internship)
JP Morgan visited our campus for FT and interns on 1st September. I sat for intern and I would like to share my interview experience which might help other students in getting an internship in JP Morgan. Around 100 students from CSE, MCA, ECE, EEE sat for interns and the process consisted of 3 rounds. Round 1 was an online test on HackerRank Platfo
3 min read
Output of C programs | Set 59 (Loops and Control Statements)
Prerequisite : Control StatementsQ.1 What is the output of this program? C/C++ Code #include &lt;iostream&gt; using namespace std; int main() { char i = 0; for (; i++; printf(&quot;%d&quot;, i)) ; printf(&quot;%d&quot;, i); return 0; } Options a) 0 1 2 ... infinite times b) 0 1 2 ... 127 c) 0 d) 1 ans:- d Explanation : Before entering into the for
3 min read
proto van Emde Boas Trees | Set 1 (Background and Introduction)
Let us consider the below problem statement and think of different solutions for it. Given a set S of elements such that the elements are taken from universe {0, 1, .... u-1}, perform following operations efficiently. insert(x) : Adds an item x to the set+ S.isEmpty() : Returns true if S is empty, else false.find(x) : Returns true if x is present i
5 min read
Practice Questions for Recursion | Set 4
Question 1 Predict the output of the following program. C/C++ Code #include &lt;iostream&gt; using namespace std; void fun(int x) { if(x &gt; 0) { fun(--x); cout &lt;&lt; x &lt;&lt;&quot; &quot;; fun(--x); } } int main() { int a = 4; fun(a); return 0; } // This code is contributed by SHUBHAMSINGH10 C/C++ Code #include&lt;stdio.h&gt; void fun(int x)
6 min read
Practice Questions for Recursion | Set 5
Question 1Predict the output of the following program. What does the following fun() do in general? C/C++ Code #include &lt;iostream&gt; using namespace std; int fun(int a, int b) { if (b == 0) return 0; if (b % 2 == 0) return fun(a + a, b/2); return fun(a + a, b/2) + a; } int main() { cout &lt;&lt; fun(4, 3) ; return 0; } // This code is contribut
5 min read
Counters in Python | Set 2 (Accessing Counters)
Counters in Python | Set 1 (Initialization and Updation) Counters in Python | Set 2Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value's count is shown as 0. Example: In this example, we are using Counter to print the key and frequency of that key. The
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Turing Machine for subtraction | Set 2
Prerequisite – Turing Machine, Turing machine for subtraction | Set 1 A number is represented in binary format in different finite automatas like 5 is represented as (101) but in case of subtraction Turing Machine unary format is followed . In unary format a number is represented by either all ones or all zeros. For example, 5 will be represented b
2 min read
Count pairs from two arrays with difference exceeding K | set 2
Given two integer arrays arr[] and brr[] consisting of distinct elements of size N and M respectively and an integer K, the task is to find the count of pairs (arr[i], brr[j]) such that (brr[j] – arr[i]) &gt; K. Examples: Input: arr[] = {5, 9, 1, 8}, brr[] = {10, 12, 7, 4, 2, 3}, K = 3Output: 6Explanation:Possible pairs that satisfy the given condi
10 min read
PayPal Interview Experience | Set 11
Round 1: Write a program to find the subsets of an array ? Write a program to find the least ancestor node of a binary tree / bst ? Write a program to find the intersection between 2 arrays ? Write a program to evaluate a boolean expression i.e String s = "(a == b) || (b == c)" ? Round 2: Explain optional class in java 8 ? what is the default threa
1 min read
Change string to a new character set
Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd....xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output :
7 min read
HP R & D Labs Interview Experience | Set 7 (For Experienced)
I would like to share my recent interview experience with HP R&amp;D Labs banglore. I have experience of 4 years into network protocol development. The opening position is for network protocol developer (Layer2/Layer3). Selected people were called for the drive. Totally, there are 5 rounds happened in a single day. (4 technical (1 written + 3 face
2 min read
Paytm Interview Experience | Set 21 (5+ Experience)
Round 1: 2 questions on mettle - online judge 1. longest palindrome of a given string. 2. There are n candies and K student. candies are distributed in a order that 1st student get 1 candy, 2nd get 2, 3rd get 3 and so on till nth student. now, 1st student gets k+1 candy, 2nd get k+2, 3rd gets k+3 and so on. if there are not enough candies to be giv
2 min read
Output of Java Programs | Set 54 (Vectors)
Prerequisite : Vectors in Java Basics 1. What is the Output Of the following Program Java Code import java.util.*; class demo1 { public static void main(String[] args) { Vector v = new Vector(20); System.out.println(v.capacity()); System.out.println(v.size()); } } Output: 20 0 Explanation: function - int capacity( ) Returns the capacity of the vect
6 min read
Article Tags :
Practice Tags :