Monday, December 14, 2009

Namespaces in C++

So... The first topic that I would like to discuss the topic of namespaces in C++. What is a namespace? Well, it's a way to group classes, objects and functions all under one name.

For instance:

namespace myNamespace
{
int x;
}


To access the variable inside the namespace, we can use the code namespace_name::variable_name:



myNamespace::x

So, now that you know somewhat about namespaces, let's get to the reason that I brought this up. Certain C++ programmers, when using a cout statement, like to use:



std::cout<<"Hello World!\n";

They put the namespace tag of std in front of the cout. A better way to do this is to say at the beginning of the code:



using namespace std;
//more code here
cout<<"Hello World!\n";

This way, you don't need the std tag. You could see how many extra strokes it would take to put std:: in front of every cin and cout? So, why do people do it? Well, the only real reason is that when you say "using namespace std;", you are including EVERYTHING in the std namespace. Maybe you don't want everything to be included. You could always say:



using std::cout;

This would replace putting the std:: tag in front of every cout; however, you wouldn't be using the entire namespace and then you wouldn't have to worry about possible class name-clashing in the future. See if there is something already named, you can't make a class with the same name yourself. For instance, if you try to make a Time class, it might not work depending on your include statements. I had this problem once and had to rename the class.

Other good things from namespaces to include: There are a lot of different things in the std namespace that can all be found at this link: http://www.cplusplus.com/reference/

Every one of those items is included when you use the std namespace. The best things, in my opinion, are the functions in cctype. If you include cctype with the following code:



#include <cctype>

,then you can have access to functions like toupper, tolower, isalpha, isdigit, etc. These functions can tell you about characters and return if the character is a number, letter, space, uppercase, lowercase, etc. and can also change a character from a lower to an upper and vice-versa.

Well, there you have it. That's the low-down on namespaces. Remember, you can create your own namespaces! Just follow the code outlined near the beginning. And if you are one of those people that use std:: before every cout and cin, start using "using std::cout" and "using std::cin" at the beginning of your code after the includes.

Next update from me? Changing colors in standard C++ console output :)

Until then,
Happy Coding,
kieblera5

No comments:

Post a Comment