Namespaces
E N D
Presentation Transcript
Namespaces How Shall I Name Thee?
Why Namespaces • by default, function, class, global constant and variable scope is global • in large programming projects multiple people may give different constructs the same name, resulting in name collision. • words like sort, find, count and print are tempting • name collision may result in • compile-time error - when header is included • linker error • namespaces– designed to sub-divide global scope and avoid name collision
Defining Namespaces • define a namespace block, declare constructs inside namespace myNamespace{ const int limt=5; void myFunc(int a){ ++a; } } • functions, classes, etc. (constructs with separate definitions) may be defined outside namespace myNamespace{ const int limt=5; void myFunc(int); } void myNamespace::myFunc(int a){ ++a; } thus structured, the namespace is non-executable and should go into a header file
Employing Namespaces several styles • always employ scope resolution operator (explicit statement of scope) for(int i=0; i < myNamespace::limit; ++i) myNamespace::myFunc(i); • import a name – specify that you are employing a specific name in this file using myNameSpace::limit; using myNameSpace::myFunc; for(int i=0; i < limit; ++i) myFunc(i); • import all names in a namespace using namespace myNamespace; for(int i=0; i < limit; ++i) myFunc(i); • do not do in headers – opens namespace for all source files including this header
Scope of Importing variables can be imported either into global scope or into a block • importing into the global scope – imported variables can be used anywhere using myNameSpace::limit; int main(void){ for(int i=0; i < limit; ++i) myFunc(i); } • importing into the scope of a function – imported variables can be used inside function only int main(void){ using myNameSpace::limit; for(int i=0; i < limit; ++i) myFunc(i); }
std • has an extensive set of names used in programs. Contains • cout, cin, endl, vector, string, etc. • three styles of employing std: • explicit scope resolution of all names • pro: safest • con: program code becomes less terse • employ using with specific names • pro: more terse • con: have to maintain name list at beginning of the file • employ using namespace std; • pro: simplest, tersest • con: unexpected names are imported: sort, find, count are in std;do not use in header files!
Review Questions • what is the scope of a function? global variable? global constant? • what is a namespace and why is it needed? • how to define a namespace? is namespace an executable statement? • how do you define a function declared in a namespace? • the three styles of employing namespaces are • explicit statement namespace • importing specific name • importing all names in a namespace how do you employ each style? what are the advantages/disadvantages of each style? • which style should be employed in a header • what happens when using is put inside/outside a function definition?