Click to See Complete Forum and Search --> : Newbie Question
slx47
May 2nd, 2002, 05:33 PM
my compiler adds this automatically:
using namespace std;
what is it and what does it do ?
CornedBee
May 2nd, 2002, 05:44 PM
namespaces are a C++ feature that allows you to group variables and functions together, but not as closely as they are in classes.
A namespace is simply that: a space in which names exist:
namespace myspace
{
int i;
float f;
}
i = 4; // doesn't work! wrong scope
myspace::i = 3; // does work, scope resolution operator
This allows you to avoid conflicts of global variables (very useful when you work on a team).
namespace a
{
int somevar;
}
namespace b
{
int somevar;
}
somevar = 3; // which one?
a::somevar = 5; // this is unambigous
b::somevar = 9;
By convention, all functions/classes/variabels in the C++ runtime library are grouped together in the large namespace std.
Because writing std::... every time may be annoying, there is the using keyword. You can use it to import certain identifiers or a whole namespace to global scope.
#include <iostream>
using std::cout; // import cout to global scope
cout << "Hello"; // now possible
cout << endl; // not possible, endl is not imported
using namespace std; // import the whole std namespace to global scope
int i;
cin >> i;
cout << i << endl; // possible, all symbols imported
I hope that clears it up some.
abdul
May 2nd, 2002, 08:45 PM
Originally posted by CornedBee
namespaces are a C++ feature that allows you to group variables and functions together, but not as closely as they are in classes.
A namespace is simply that: a space in which names exist:
[code]
namespace myspace
{
int i;
float f;
}
Just curious, what if declared a variable called "i" outside the namespace myspace? I hope it won't give you any error and will let you use that ouside i.
nabeels786
May 2nd, 2002, 08:52 PM
you can still use it
if you had
int i;
void blah(){
int i;
}
you can access the global i like
::i
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.