"Anonymous" <no@spam.net> wrote in message
news:q3********************************@4ax.com
Is namespace the same thing as scope? While reading the book
"Thinking in C++", I was under the impression that namespace is, well,
a namespace--a feature to create a hiearchy for identifiers within the
Global Namespace. And that, all identifiers within a given namespace,
however deeply nested they are, each of them has the Global Scope.
So, if
namespace outer {
int a = 1;
namespace inner {
int b = 2;
void myprint () { cout << a;}
//can I do this, and will it print 1?
}
Yes.
then both outer::a and outer::inner:b variables will have global
scope, and both variables can be accessed from all the other
scopes--function, class, and block scopes--provided they are not
overridden within the other scope. Can someone help clarify the
difference between namespace and scope for me? I'm confused.
You seem to basically have it right. For the most part, a namespace just
creates naming rules for variables. The one case in which a variable
declared in a namespace is not accessible elsewhere is when an unnamed
namespace is used, e.g.,
namespace
{
int a, b;
// other stuff
}
In this case, it is not possible to refer to a or b outside the namespace.
The word "scope" is used with more than one meaning. One sense is that
destructors are called when control passes outside of a scope. Namespaces
are *not* scopes in that sense.
Another sense is the way in which "scope" is used when referring to "class
scope". A variable x or function foo with class scope can be referred to
directly as x or foo, respectively, by all member functions of the class.
Outside of the class, x and foo can only be referred to via class objects or
(in the case of static members) by using the class name --- and then only if
the caller has the required access privileges. Namespaces behave similarly
and in this sense do define a scope. That is why :: is called the "scope
resolution operator". A namespace is actually somewhat similar to a class in
which all data and functions are both public and static.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)