views:

894

answers:

4

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()
    {
    }
+2  A: 

You can try using ::glob--; instead. This way you tell the compiler to use the global namespace.

Marc
+1  A: 

Class member will be used here, to access global variable use :: operator.

Lazin
+4  A: 

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

yesraaj
+8  A: 

Variables and functions are accessed using scoping rules, not visbility rules. Because F::glob is the glob in the scope of W::test(), it is used. However, W::test() does not have access to F::glob, and an error results. The compiler does not check for ::glob because something else preceeds it in scope "priority" (not sure for the exact term).

strager