5.2.4 · Coding › C++ Programming
Intuition Badi idea kya hai
Socho ek classroom mein do students hain jinke naam dono "Alex" hain. Teacher chillata hai "Alex!" — chaos: kaun wala?
Ek namespace aise hai jaise har Alex ko ek surname dena: MathLib::Alex vs Physics::Alex.
Chhota naam same, full naam alag → koi confusion nahi.
Code bilkul yahi hai: do libraries dono print() ya max define kar sakti hain. Namespaces names ko ek labelled box mein wrap karte hain taaki compiler ko hamesha pata rahe ki kiska print mean kar rahe ho.
Ek namespace ek named scope hota hai jo related identifiers (functions, classes, variables, types) ko group karta hai taaki unke fully-qualified names unique ban jayein.
namespace Name { ... } se declare kiya jaata hai.
Ek member ko scope-resolution operator :: se access karo → Name::member.
Global scope khud ek unnamed namespace hai, jisko ::name se reach kar sakte ho.
namespace Geometry {
double area ( double r ) { return 3.14159 * r * r; } // a circle
}
namespace Statistics {
double area ( double base , double h ) { return 0.5 * base * h; } // unrelated "area"
}
int main () {
double a = Geometry :: area ( 2.0 ); // 12.566...
double b = Statistics :: area ( 3.0 , 4.0 ); // 6.0
}
Intuition Collision ki problem
Ek program kaafi saare .cpp/.h files se banta hai, aksar alag-alag authors aur libraries ke. Agar library A aur library B dono global int counter; ya void log(); define karein, toh linker ko ek naam ke saath do cheezein dikhti hain → ODR (One Definition Rule) violation ya ambiguous call. Program compile/link nahi hoga.
Namespaces har author ko unke naam apne rakhne dete hain bina duniya mein kisi aur se coordinate kiye.
Worked example Classic clash:
std::count
Standard library std::count define karta hai. Agar tum bhi ek variable count chahte ho, usse std:: mein daalna illegal hoga, lekin tumhara khud ka count global scope mein rakhna shadowing ka risk ya readers ko confuse kar sakta hai. Apna wrap karo: App::count. Dono saath exist karte hain.
Definition Naam tak pahunchne ke teen tarike
Fully qualified : std::cout — hamesha unambiguous, verbose.
using-declaration : using std::cout; — sirf ek naam laata hai.
using-directive : using namespace std; — sab kuch laata hai (headers mein risky!).
#include <iostream>
void demo () {
std ::cout << "A \n " ; // (1) qualified
using std ::cout; // (2) sirf cout
cout << "B \n " ;
using namespace std ; // (3) sab kuch (headers mein avoid karo)
cout << "C \n " ;
}
Yeh woh darwaza dobara khol deta hai jo humne band kiya tha: yeh saare std names ko current scope mein dump kar deta hai, toh tumhara distance, count, swap achanak std::distance wagera se clash kar sakta hai. Ek chote .cpp mein theek hai; header mein dangerous kyunki jo bhi file use include karti hai ushe yeh pollution mili jaati hai.
:: uniquely resolve kyon karta hai
Namespace ko ek prefix string samjho jo har naam ke aage laga diya jaata hai. Compiler, har naam ke liye jo tum likhte ho, candidate full names ka ek set maintain karta hai. Foo::bar candidate set ko exactly {Foo::bar} tak force karta hai. Ek unqualified bar name lookup trigger karta hai: current scope mein search karo → enclosing namespaces → using se visible ki gayi cheezein. Jo pehla scope match deta hai woh jeetta hai; agar ek scope do equally-good matches deta hai → ambiguity error .
namespace Company {
namespace Project {
namespace Net { int port = 8080 ; }
}
}
int x = Company :: Project :: Net ::port; // verbose!
namespace CPN = Company :: Project :: Net ; // namespace alias
int y = CPN ::port; // tidy
// C++17 shorthand for nesting:
namespace Company :: Project :: Net { int retries = 3 ; }
Intuition Aliases kyon help karte hain
Lambe prefixes unique hote hain lekin unreadable. Ek alias uniqueness khoye bina ek chhota local synonym deta hai — dono worlds ka best. Socho ek lambe address ko "Home" naam se contact mein save karna.
namespace { // unnamed → unique to THIS translation unit
int secretHelper = 0 ;
void onlyHere () {}
}
Definition Unnamed namespace
Ek unnamed namespace apne members ko internal linkage deta hai — sirf current .cpp file ke andar visible. Yeh purane file scope static keyword ka modern replacement hai: helpers ko private rakhne aur doosri file mein same naam se clash avoid karne ke liye use karo.
using namespace std; har jagah sirf convenient hai."
Kyun sahi lagta hai: kam typing, tutorials mein yahi hota hai, chote programs theek chalte hain.
Kyun daata hai: Headers mein yeh har includer ko pollute karta hai; yeh silently tumhara std::distance pick kar sakta hai tumhare ki jagah, behavior badal ke. Fix: qualify karo (std::cout) ya targeted using std::cout; use karo sirf functions ya .cpp files ke andar .
Common mistake "Namespace mein code daalna use hide / private karta hai."
Kyun sahi lagta hai: yeh { } mein wrap hai jaise class.
Fix: Namespaces sirf rename karte hain; andar ki sab cheezein Ns::member se globally reachable hain. Privacy ke liye private: (classes) ya unnamed namespaces (file-local) use karo.
Common mistake "Main same namespace mein same variable do files mein redefine kar sakta hoon."
Kyun sahi lagta hai: woh 'same box' mein hain, organised lagta hai.
Fix: Namespace open hota hai aur files ke across span karta hai, toh do .cpps mein Ns::x define karna = ek entity ki do definitions → ODR violation/linker error. Header mein extern se declare karo, ek baar define karo.
::name ka matlab global wala hai bhool jaana.
Jab ek local using ne swap ko shadow kar diya, tum phir bhi ::swap ya std::swap se global/std wale ko force kar sakte ho. Leading :: = "lookup bilkul upar se start karo."
Worked example Example 1 — Ambiguous call resolve karna
namespace A { void f () {} }
namespace B { void f () {} }
using namespace A ;
using namespace B ;
// f(); // ERROR: ambiguous — both A::f and B::f visible
A :: f (); // OK
Yeh step kyon? Do using-directives dono fs ko equal rank ke saath lookup mein daalta hai → ambiguity. A:: se qualify karna candidate set ko ek tak shrink karta hai.
Worked example Example 2 — Library author users ko protect karta hua
namespace JsonLib {
class Value { /* ... */ };
Value parse ( const std :: string & s );
}
// user's file:
int parse = 5 ; // user's apna 'parse' — koi clash nahi!
auto v = JsonLib :: parse ( "{}" ); // library's parse, explicitly
Yeh step kyon? Library ne parse ko JsonLib mein wrap kiya, toh user ka global parse aur library ka JsonLib::parse ke different full names hain — dono ek saath legal hain.
Worked example Example 3 — Implementations switch karne ke liye alias
namespace FastImpl { int sqrt_ ( int x ){ return /*approx*/ x; } }
namespace ExactImpl { int sqrt_ ( int x ){ return /*exact*/ x; } }
namespace Active = FastImpl ; // ek line mein switch karo
int r = Active :: sqrt_ ( 16 );
Yeh step kyon? Ek alias line badalne se har Active:: call redirect ho jaati hai — zero collisions ke saath ek clean compile-time strategy switch.
Recall Woh 20% jo 80% deta hai
Namespace = ek prefix box jo names ko :: se unique banata hai.
Names tak pahuncho: qualified Ns::x, using-declaration using Ns::x;, using-directive using namespace Ns;.
Kabhi bhi header mein using namespace mat daalo.
Namespaces open hote hain (files ke across span karte hain) aur privacy provide nahi karte .
Unnamed namespace = file-local (internal linkage).
Recall Feynman: ek 12-saal ke bacche ko samjhao
Class mein do bacche hain jinhe dono Sam kehte hain. Mix-up se bachne ke liye hum kehte hain "Sam Brown" aur "Sam Green" — surname se pata chalta hai kaun hai. Code mein, namespace surname hai. Jab tum Math::Sam likhte ho tumhara matlab Math-team wala Sam hai, doosra kabhi nahi. Agar tum sirf "Sam" kaho aur do Sams visible hain, teacher confuse ho jaata hai aur class rok leta hai (ek error) — isliye tum surname add karte ho clear hone ke liye.
Mnemonic Access styles yaad karo
"Q-D-D: Qualify, Declare one, Dump all."
Q ualify → std::cout
D eclare one → using std::cout;
D ump all → using namespace std; (dangerous wala — Dump = Dangerous ).
Scope and Storage Duration — namespaces ek tarah ka named scope hain.
One Definition Rule (ODR) — collisions actually ODR violations hain.
Header Files and Include Guards — kyon using namespace headers mein spread hota hai.
Classes and Encapsulation — true privacy vs namespace grouping.
Linkage — internal vs external — unnamed namespaces aur static.
The Standard Library (std) — sabse bada real-world namespace.
Namespaces kya problem solve karte hain? Name collisions — yeh identifiers ke full names ko unique banate hain taaki do libraries dono ek chhote naam jaise print use kar sakein.
Namespace member access karne wala operator kaunsa hai? Scope-resolution operator ::, jaise Ns::member.
Using-declaration aur using-directive mein kya fark hai? Using-declaration using std::cout; ek naam laata hai; using-directive using namespace std; saare naam laata hai.
Header mein using namespace std; kyun avoid karein? Yeh har us file ko pollute karta hai jo header include karti hai, clashes ka risk aur silently altered name lookup ka khatre ke saath.
Kya namespaces privacy/hiding provide karte hain? Nahi — members Ns::member se reachable rehte hain. Privacy ke liye classes ka private: ya unnamed namespaces use karo.
Unnamed namespace apne members ko kya deta hai? Internal linkage — visibility us ek translation unit tak limited hoti hai (file-scope static ka modern replacement).
Leading ::name ka matlab kya hai? Global namespace mein lookup start karo (locally using-inject kiye gaye names skip karo).
Kya namespaces files ke across open ya closed hain? Open — tum same namespace mein multiple files mein dobara enter kar sakte ho; names accumulate hote hain (lekin har definition phir bhi ODR follow karta hai).
Company::Project::Net ko kaise shorten karein?Namespace alias se: namespace CPN = Company::Project::Net;.
Do identifiers kab collide karte hain? Tabhi jab unke fully-qualified names identical hoon jabki woh different entities ko refer karte hon.
ODR violation or ambiguity
namespace Name curly braces
Scope-resolution operator ::
using-declaration: one name
using-directive: all names