Lecture 1.3
Lecture 1.3
• Introduction to namespace
1
Namespace
• Namespaces provide a method for preventing name
conflicts in large projects.
• Symbols declared inside a namespace block are placed
in a named scope that prevents them from being
mistaken for identically-named symbols in other scopes.
• Multiple namespace blocks with the same name are
allowed. All declarations within those blocks are
declared in the named scope.
2
Defining a Namespace
3
Example:
#include <iostream>
using namespace std;
// first name space
namespace first_space { Output:
void func() { Inside first_space
Inside second_space
cout << "Inside first_space" << endl;
}
}
// second name space
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
int main () {
// Calls function from first name space.
first_space::func();
5
Example:
#include <iostream>
using namespace std;
// first name space
namespace first_space { Output:
Inside 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;
}
6
Summary