Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
c++ namspaces
02-15-2010, 01:02 AM (This post was last modified: 02-15-2010 02:29 AM by drdebcol.)
Post: #1
c++ namspaces
Namespaces
Namespaces address the problem of naming conflicts between different pieces of code. For example, you might be writing some code that has a function called foo(). One day, you decide to start using a third- party library, which also has a foo() function. The compiler has no way of knowing which version of foo() you are referring to within your code. You can’t change the library’s function name, and it would be a big pain to change your own.
Namespaces come to the rescue in such scenarios because you can define the context in which names are defined. To place code in a namespace, simply enclose it within a namespace block:
Code:
// namespaces.h
namespace mycode { void foo();
}
A Crash Course in C++
The implementation of a method or function can also be handled in a namespace:
// namespaces.cpp
#include <iostream> #include “namespaces.h”
namespace mycode {
void foo() { std::cout << “foo() called in the mycode namespace” << std::endl;
}
}
By placing your version of foo() in the namespace “mycode,” it is isolated from the foo() function provided by the third-party library. To call the namespace-enabled version of foo(), prepend the namespace onto the function name as follows.
mycode::foo(); // Calls the “foo” function in the “mycode” namespace
Any code that falls within a “mycode” namespace block can call other code within the same namespace without explicitly prepending the namespace. This implicit namespace is useful in making the code more precise and readable. You can also avoid prepending of namespaces with the using directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the code that follows:
Code:
// usingnamespaces.cpp
#include “namespaces.h”
using namespace mycode;
int main(int argc, char** argv) {
foo(); // Implies mycode::foo();
}
Visit this user's website Find all posts by this user
Quote this message in a reply
02-15-2010, 02:31 AM
Post: #2
RE: c++ namspaces
Very good explanation. Namespaces are really important part of C++ !

OFFTOPIC :
I edited your post because you used php tags and that made post too long to the right because text inside was too long to the right. So i used simple code tags where codes are.

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: