CS 212 Object Oriented Analysis and Design Namespace
CS 212: Object Oriented Analysis and Design Namespace
Introduction • Purpose is to localize the names of identifiers to avoid name collisions • Global namespace • Name defined by one library would conflict with the same name defined by the other library • Namespace allows the same name to be used in different contexts without conflicts arising • e. g. std
Namespace Fundamentals • Allows you to partition the global namespace • Creating a declarative region i. e. a namespace defines a scope • Inside a namespace, identifiers declared within that namespace can be referred to directly • Scope resolution operator to be used to refer to objects declared within a namespace from outside that namespace • Demonstration: namespace 1. cpp
The ‘using’ keyword • Use of : : always is a tedious task • The using statement was invented to alleviate this problem • The using statement has these two general forms using namespace name; using name: : member; using Counter. Name. Space: : lowerbound; Demonstration: namespace 2. cpp
Nested Namespace • • Namespace defined within another namespace Scope resolution operator to be used Namespace 1: : Namespace 2: : member Namespace 1: : member Object Oriented Analysis and Design (CS 212)
Unnamed Namespaces • A special type of namespace, called an unnamed namespace • Allows to create identifiers that are unique within a file • To establish unique identifiers that are known only within the scope of a single file • Outside the file, the identifiers are unknown • Demonstration (file 1 & file 2. cpp)
Namespace Alias • Alias (alternate name) can be assigned to a namespace • Ease of programming • Similar to typedef Object Oriented Analysis and Design (CS 212)
Koening Lookup • Argument-dependent lookup, also known as ADL, or Koenig lookup • Set of rules for looking up the unqualified function names • function-call expressions, including implicit function calls to overloaded operators • These function names are looked up in • The namespaces of their arguments • The scopes and namespaces considered by the usual unqualified name lookup. Object Oriented Analysis and Design (CS 212)
Advantage of Koening Lookup my. Line l 1(point(2, 5), point(9, 10)); std: : cout << “equation of line is: ”; std: : cout << l 1 << end; Object Oriented Analysis and Design (CS 212)
In a nutshell Standard namespace User defined namespace Variables Functions Classes
The std namespace • Standard C++ defines its entire library in its own namespace called std • using namespace std; • This causes the std namespace to be brought into the current namespace • Direct access to the names of the functions and classes defined within the library without using std: :
- Slides: 11