Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.
Namespace is a feature that provides a way to group related identifiers such as variables, functions, and classes under a single name. It provides the space where we can define or declare identifier i.e. variable, method, classes. In essence, a namespace defines a scope.
Namespace Definition
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
C++ namespace name { // type1 mamber1 // type2 mamber2 // type3 mamber3 . . . . . . }
It is to be noted that, there is no semicolon (;) after the closing brace.
For example,
C++ // Define a namespace called 'first_space' namespace first_space { void func() { cout << "Inside first_space" << endl; } }
Accessing Members
We can access the members of namespace using scope resolution operator(::).
Syntax:
C++ namespace_name::member_name;
Example:
C++ #include <iostream> // Define a namespace called 'first_space' namespace first_space { void func() { std::cout << "Inside first_space" << std::endl; } } int main() { // Access member of namespace first_space::func(); return 0; }
Namespace with using Directive
We 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.
C++ #include <iostream> namespace first_space { void func() { std::cout << "Inside first_space" << std::endl; } } // Using first_space using namespace first_space; int main() { // Call the method of first_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.
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:
C++ #include <iostream> namespace first_space { void func() { std::cout << "Inside first_space" << std::endl; } } // Using first_space using first_space::func; int main() { // Call the method of first_space func(); return 0; }
Nested Namespace
We can nest one namespace into another. Such namespaces are called nested namespaces.
Example:
C++ // Outer namespace namespace outer { void fun(){ cout << "Inside outer namespace" << endl; } // Inner namespace namespace inner { void func() { cout << "Inside inner namespace"; } } }
Accessing members in nested namespaces require multilevel scope resolution as shown:
C++ #include <iostream> using namespace std; // Outer namespace namespace outer { void fun(){ cout << "Inside outer namespace" << endl; } // Inner namespace namespace inner { void func() { cout << "Inside inner namespace"; } } } int main() { // Accessing member of inner // namespace outer::inner::func(); return 0; }
OutputInside inner namespace
In-built Namespaces
C++ already uses some inbuilt namespaces that we are already familiar with. Let's look at some of the common ones:
std Namespace
In C++, std namespace is the part of standard library, which contains most of the standard functions, objects, and classes like cin, cout, vector, etc. It also avoids conflicts between user-defined and library-defined functions or variables.
C++ #include <iostream> using namespace std; int main() { int a = 3, b = 7; // 'cout' and 'endl' are part of the std namespace cout << "Sum: " << a + b ; return 0; }
Note: ADL (Argument-Dependent Lookup) in C++ is a feature that automatically searches for functions or operators based on the types of the function's arguments.
Global Namespace
The global namespace is the default namespace where all the functions, variables, and classes that are not explicitly declared inside any namespace. Everything outside of any namespace is considered to belong to the global namespace.
We can access the global namespace using scope resolution operator(::) followed by global namespace name.
Example:
C++ #include <bits/stdc++.h> using namespace std; int n = 3; int main() { int n = 7; // Accessing global namespace cout << ::n << endl; cout << n; return 0; }
Extending Namespace
In C++, extending a namespace means adding more features (like functions, variables, or classes) to an existing namespace, even if that namespace was defined somewhere else (like in a library or another file).
Example:
C++ #include <bits/stdc++.h> using namespace std; namespace nmsp{ void func(){ cout << "You can extend me" << endl; } } // Extending the same namespace namespace nmsp{ void func2(){ cout << "Adding new feature"; } } int main() { nmsp::func(); nmsp::func2(); return 0; }
OutputYou can extend me Adding new feature
Creating an Alias for Namespace
We can also create an alias of existing namespace using namespace.
C++ namespace namespace_name{ // Members of namespace } // Creating a alias of namespace_name namespace nn = namespace_name;
Inline Namespace
An inline namespace is a type of namespace where its members are accessible directly without using the namespace name.
Example:
C++ #include <iostream> using namespace std; inline namespace inline_space { void display() { cout << "Inside inline namespace"; } } int main() { // Direct access due to inline namespace display(); return 0; }
OutputInside inline namespace
Anonymous Namespace
A namespace does not have a name called an anonymous namespace. It ensures that the entities in the unnamed namespace are limited to that file.
Example:
C++ #include <iostream> using namespace std; // Anonymous namespace namespace { int value = 10; } int main() { // Accessing anonymous namespace variable cout << value; return 0; }
Namespace vs Class
Namespaces and classes may look similar, but they are completely different. The differences between namespaces and classes are shown below:
Namespace | Class |
---|
It is used to organize code and prevent name collisions in large projects. | Used to define and create objects that encapsulate data and behavior. |
Does not encapsulate data or behavior; it only provides scope. | Encapsulates both data members and methods into objects. |
Does not have access modifiers (public, private, protected). | Has access modifiers (public, private, protected) to control the visibility of members. |
Cannot be inherited. | Can be inherited to create subclasses. |
A namespace is not instantiated; it is used to group entities. | A class is instantiated to create objects. |
Does not directly consume memory; it only provides scope for identifiers. | Consumes memory as objects are created from a class. |
Used to organize code and avoid name conflicts, especially in large projects. | Used to create objects and model real-world entities with attributes and behaviors. |
No constructors or destructors. | Has constructors and destructors to initialize and destroy objects. |
Similar Reads
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem