CSC/ECE 517 Fall 2010/ch2 4d RB
Introduction
Namespaces are used in Computer Science to group similar items into different logical units, so that one item can be un-ambigously differentiated from another item. Trivial it may seem, but creating namespaces is one of the most basic activities of modern day programming. It makes a program more organized and less prone to errors.
Why namespaces
In general programming languages like C++, variable names, function names, structure names, class names, union names and enumerations fall under one general category called names. While writing big programs involving several programmers, the situation is likely to go out of hand if proper control is not exercised on the visibility of these names. For example, lets consider the following:
//library1.h char hello(); void print(); class EmpSal { char* ename; int esal; }
// library2.h char hi(); void print(); class EmpSal { char* nm; float tax; }
In the above examples, we have two header files, library1.h and library2.h which have the function void print() and class EmpSal. Now if both the header files are included in a program (see below) and a reference to the class is made, or the function is called, then this situation becomes ambiguous.
//prog.c #include "library1.h" #include "library2.h" void main() { print(); // ambiguous call EmpSal es = new EmpSal(); // ambiguous reference EmpSal a class }