ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

C++ chapter 37: Namespace in C++

prodevelopertutorial February 26, 2020
In this chapter we shall learn about below topics:
1. Introduction
2. Declaring namespaces
3. Accessing namespace using “using” directive
4. The global namespace
5. The std namespace
6. Nested namespaces
7. Inline namespaces (C++ 11)
8. Namespace aliases
9. Anonymous or unnamed namespaces
10. Discontiguous Namespace in C++

1. Introduction

Namespace are used to provide scope for the identifiers like functions, variables, classes etc, with the same name available in different libraries.
All identifiers inside a same namespace are visible to one another.
The identifiers outside the namespace scope can be accessed by using fully qualified name for each identifier. For example “std::vector<std::string> vec;”.
The variables declared in 2 different namespace can have same name.

2. Declaring namespaces 

“namespace” is the keyword is used to declare a namespace.
Below is the way to declare a namespace:
namespace MyNamespaceName

{

//code declarations

}


The identifiers can be accessed by scope resolution operator.
Example:
MyNamespaceName::code;
Full code example:
#include <iostream>  




// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;  







// First namespace

namespace FirstNameSpace 

{

   void func() 

   {

      cout << "Inside FirstNameSpace" << endl;

   }

}




// Second namespace

namespace SecondNameSpace 

{

   void func() 

   {

      cout << "Inside SecondNameSpace" << endl;

   }

}




int main () 

{

   // Calling first namespace

   FirstNameSpace::func();

   

   // Calling second namespace

   SecondNameSpace::func(); 




   return 0;

}
Output:
Inside FirstNameSpace

Inside SecondNameSpace

3. Accessing namespace using “using” directive

You can access the namespace by using “using” directive.
#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;  


// First namespace

namespace FirstNameSpace 

{

   void func() 

   {

      cout << "Inside FirstNameSpace" << endl;

   }

}


using namespace FirstNameSpace;

int main () 

{

   func();

  

   return 0;

}


4. The global namespace

Identifiers defined outside of all the namespaces will be called as global namespaces. It is recommended not to create a global namespace. An exception is for the entry point for main function, that requires global namespace to work.
To access an global namespace identifier use  scope resolution operator “::”.
For example:

::myGlobalFunction();
This will differentiate between the global identifier and any other local identifier with the same name.

5. The std namespace

All of the standard C++ libraries are defined in “std” namespace or nested inside “std” namespace.

6. Nested namespaces

Namespace can be declared inside another namespace. Then it is called as Nested namespace.
Example:
#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;  


namespace OutsideNamespace 

{

    int a;

    int b;

    // Second namespace

    namespace InsideNamespace 

    {

       void add(int num1, int num2) 

       {

          cout << "Sum is "<<(num1 + num2) << endl;

       }

    }

}



int main () 

{

   OutsideNamespace::a = 10;

   OutsideNamespace::b = 20;


   OutsideNamespace::InsideNamespace::add(OutsideNamespace::a, OutsideNamespace::b);

   return 0;

}
Output:
Sum is 30

7. Inline namespaces (C++ 11)

Inline namespaces are introduced in C++ 11.
Inline namespaces are used as a nested namespace.
They are treated as a normal namespace instead of treating as a nested namespace.
Example:
#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;  



namespace Foo 

{

    // Inline namespace

    inline namespace Bar 

    {

       void barFun() 

       {

          cout << "In bar Func"<< endl;

       }

    }

}


int main () 

{

    //barFun can be called with the parent namespace

    Foo::barFun();

   return 0;

}


Output:
In bar Func

But what is the use of inline namespace?

It is useful in version control. Suppose you released new updated version of a function and it is not backward compatible. At that time you can use inline namespace.
It can be shown as below:
#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;  

namespace Foo 

{

    namespace v1

    {

       void fooFun() 

       {

          cout << "In old foo Func"<< endl;

       }        

    }

    // Inline namespace

    inline namespace v2 

    {

       void fooFun() 

       {

          cout << "In new foo Func"<< endl;

       }  

    }

}


int main () 

{

    //now if you cann fooFun(), latest v2 fooFun will be called.

    Foo::fooFun();

    
    //now if the user wants the older function to be called, then he can call as below:

    Foo::v1::fooFun();


   return 0;

}
Output:
In new foo Func

In old foo Func  


8. Namespace aliases

You can give another name for a namespace.
Example:
#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;  

namespace this_namespace_name_is_long 

{

    void foo()

    {

        cout<<"In foo function"<<endl;

    }

}

namespace stortName = this_namespace_name_is_long;


int main () 

{

    stortName::foo();
   return 0;

}
Output:
In foo function

9. Anonymous or unnamed namespaces

Creating a namespace without any name is called as anonymous or unnamed namespaces.
It is used to create internal linkage for functions and classes declared inside the namesapce. They can be accessed inside the file that they are declared.
The same functions and classes cannot be accessed from other file.
Example:
#include <iostream>  

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;  


namespace 

{

    void foo()

    {

        cout<<"In foo function"<<endl;

    }

}


int main () 

{

    foo();

   return 0;

}

Output:
In foo function

10. Discontiguous Namespace in C++

C++ allows you to define a same namespace spread in various files.
Then during the compilation step it will be combined.
Example:
namespace namespace_name 

{

   // declarations

}


List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT