Reputation: 27
I'm a C developer and just recently switch to C++ so namespace is new thing to learn. The A class has a static method validate(), thus it can only access static variables or constants of the A class. But if the A.cpp has a constant defined in a namespace, the val() is able to use the constant and the code below was compiled properly.
A.h
class A
{
public:
A();
static bool validate(const int num);
};
A::A()
{
// Do nothing. Just an example.
}
A.cpp
namespace A_local_constants
{
const int val = 1;
}
using namespace A_local_constants;
bool A::validate(const int num)
{
return (num == val);
}
So my question is:
Why is the static function validate() able to use the non-static constant val?
Where is the val created in the memory?
What scope is this constant?
Is it always created in the memory without the A object being created?
Upvotes: 1
Views: 93
Reputation: 2102
1) "using namespace A_local_constants;" this statement drags out all symbols defined within A_local_constants, hence bool A::validate(const int num) can refer to val.
2) Global memory
3) The scope of this contant is within A_local_constants and also will be made visible in all those places where we use "using namespace A_local_constants" or "using namespace A_local_constants::val"
4) There is no relation between class A and the constant val.
Note: "using namespace some_name_space" should be used judiciously as they may unnecessarily pollute the current namespace.
Upvotes: 1