Why use name space in program | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why use name space in program

15th Dec 2016, 12:02 PM
kashish
2 Answers
+ 4
Hello , Its used to Avoid same name conflicts in C++ . A naming conflicts occurs when two identifiers are introduced into same scope . when this happen compiler throw an Error because it does not have enough of information to resolve the Ambiguity. As program get larger, the number of identifiers increases linearly, which it turn cause the probability of naming collision to increase exponentially . let have an very Clear example .. let's say fun.h ( file name ) int do (int x, int y) { return x+y} fun2.h(another file ) int do (int x , int y) { return x-y; } main.CPP #include "fun.h" #include"fun2.h" #include <iostream> int main() { std:: cout << do(10, 3) return 0; } guess What will the output and which do function will be called by main ???? Answers : The compiler issues error : if fun.h and fun2.h are compiled separately, they will each compile without incident. however by including them in main.cpp program we get error , with the same name and parameter into the same scope (globalvia scope ) which causing a naming collision . in order to help address this type of problems , the concept NAMASPACE was introduced . Now let me give u a brief intro about Namespace namespace defines area of code in which all identifiers are guaranteed to be unique. in order to help avoid issues where two independent pieces of code have naming collision with each other when used together . we are thankful Bjan Stroustrup fro building such amazing programming language ever . c++ offers declare our own namespace via namespace keyword . take above example fun.h namespace fun { int do(int x , int y) { return x+y; } fun2.h namespace fun2 { int do (int x , int y) { return x-y;} main.cpp include "fun.h" include "fun2.h" include <iostream> int main () { std::cout <<fun::do (1,3) \\ fun do () called std::cout <<fun2::do(4,5)\\fun2 do () called return 0; } Note (::) its scope resolution operator HOPE YOU UNDERSTOOD .... THANK YOU !
15th Dec 2016, 12:25 PM
Mock
Mock - avatar
0
Namespace is used to avoid clashing of names of classes. A class declared in another namespace can have the same class name as that of other class in another namespace
15th Dec 2016, 12:09 PM
Varshil Shah
Varshil Shah - avatar