LECTURE 8 : C++ NAMESPACE
C++ NAMESPACE
� Namespaces allow to group entities like classes, objects (variables) and
functions under a name
� Global scope is divided into "sub-scopes", each one with its own name
� Useful in the case that there is a possibility that a global object or function uses
the same identifier as another one, causing redefinition errors
2
C++ NAMESPACE
� The format of namespaces is:
namespace identifier {
entities
}
� Identifier is any valid identifier
� Entities is the set of classes, objects and functions that are included within the
namespace
3
C++ NAMESPACE
#include <iostream>
using namespace std;
namespace first {
int var = 5;
}
namespace second {
double var = 3.1416;
}
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
} 4
C++ NAMESPACE
#include <iostream> int main () {
using namespace std; using first::x;
namespace first { using second::y;
int x = 5; cout << x << endl;
int y = 10; cout << y << endl;
} cout << first::y << endl;
namespace second { cout << second::x << endl;
double x = 3.1416; return 0;
double y = 2.7183; }
}
5
C++ NAMESPACE
#include <iostream> int main () {
using namespace std; using namespace first;
namespace first { cout << x << endl;
int x = 5; cout << y << endl;
int y = 10; cout << second::x << endl;
cout << second::y << endl;
}
return 0;
namespace second {
}
double x = 3.1416;
double y = 2.7183;
}
6
C++ NAMESPACE
#include <iostream> int main () {
using namespace std; {
namespace first { using namespace first;
int x = 5; cout << x << endl;
int y = 10; }
} {
namespace second { using namespace second;
double x = 3.1416; cout << x << endl;
double y = 2.7183; }
} return 0;
}
7
C++ NAMESPACE
� Unnamed namespace
⚫ Create identifiers that are unique within a file
� The format of unnamed namespaces is:
namespace {
entities
}
� Within the file that contains the namespace
⚫ the members can be used directly, without qualification
� Outside of the file
⚫ the identifiers are unknown
8
Acknowledgement
http://faizulbari.buet.ac.bd/Courses.html
http://mhkabir.buet.ac.bd/cse201/index.html
THE END
Topic Covered: Sections 13.1