In the following code, g++ gives this error :
1.cpp: In member function void W::test()':
1.cpp:6: error: int F::glob' is private
1.cpp:19: error: within this context
But, shouldn't the globally declared variable 'glob' be used here, instead of the "private" "glob"?
#include <iostream.h>
int glob;
class F
{
int glob;
public:
void readIt()
{
cin >> glob;
}
};
class W : public F
{
public:
void test()
{
glob--;
}
};
int main()
{
}
-
You can try using
::glob--;instead. This way you tell the compiler to use the global namespace. -
Class member will be used here, to access global variable use :: operator.
-
private glob shadows the global glob,so the error is correct use ::glob to access the global variable if u intent to use global variable
-
Variables and functions are accessed using scoping rules, not visbility rules. Because
F::globis theglobin the scope ofW::test(), it is used. However,W::test()does not have access toF::glob, and an error results. The compiler does not check for::globbecause something else preceeds it in scope "priority" (not sure for the exact term).
0 comments:
Post a Comment