User Program Communication

Namespaces in C++

Namespaces allow the grouping of named entities within a certain area in a program. It is used to reduce collisions of entities with the same name.


Syntax
//declaring a namespace
namespace name_of_namespace{
    //entities, which may include methods or variables
}

//accessing a member of a namespace, not being 'used'
name_of_namespace::member;

//to use a namespace within a certain area
using namespace std;
//to access a member of a namespace being used
member_of_std

Notes

If you do not want to type the namespace every time a member is accessed, you can 'use' the namespace. It is good practice not to 'use' a namespace (an exception is std).


Example
//namespace declaration
namespace mathFunctions {
    int max(int a, int b) { return a > b ? a : b ;}
}

//access a member of that namespace
int newNumber = mathFunctions::max(3, 5);

See Also
Documentation

Name visibility - C++ Tutorials

Add to Slack

< Including Header Files   |   Read from Text File >

© 2019 SyntaxDB. All Rights Reserved.