View Single Post
Old 09-06-2005, 04:44 PM   #6 (permalink)
Locutus
Registered User
 
Join Date: Aug 2005
Posts: 20
Locutus is on a distinguished road
Quote:
Originally Posted by Salchester
Can you use basic coding please, as i don't understand this! I haven't got a clue on how this works.

How come everybody uses the std:: coding?

Many Thanks
Namespaces you mean?

In short, namespaces are a way to group related stuff, like groups of functions and variables together.

Suppose you declare a namespace "my", with a function "f"
Code:
namespace my
{
        void f();
}
You can then call f() by writing
Code:
my::f();
Apart from keeping your code organised, one of the more usefull things about using namespaces is that it helps prevent name clashes.

Suppose you had two headers, my.h and your.h, each of which declare a number of functions and variables.

Code:
//my.h
int i;
void f();
bool g();

//your.h
char c;
void f();
void h();
Now, you can't include both at the same time, because the function "void f()" is declared in both headers.

If, on the other hand you put the declarations each in their own namespace, you can.
Code:
//my.h
namespace my
{
        int i;
        void f();
        bool g();
}

//your.h
namespace your
{
        char c;
        void f();
        void h();
}
And call with
Code:
my::f();
your::f();
There is actually a lot more stuff to know about namespaces, but that's pretty much the basis. Pretty much all the stuff in the standard library is inside the namespace "std", thus all the stuff like std::string, std::ofstream, etc.

For historical reasons however, there are usually two "versions" of most headers in the standard library. Eg, #include <string.h> and #include <string>, #include <iostream.h> and #include <iostream>, etc.

The difference is that the "traditional", .h versions of the headers declare everything in the global namespace, while the versions without the .h put it inside the "std" namespace.

Code:
#include        <iostream>

int main()
{
        std::cout << "Hello World!" << std::endl;

        return 0;
}
vs
Code:
#include        <iostream.h>

int main()
{
        cout << "Hello World!" << endl;

        return 0;
}
The version with namespaces is generally preferred.
Locutus is offline   Reply With Quote