Shirley Feng
Shirley Feng

Reputation: 143

Accessibility and Visibility in Nested Class C++

I wrote the following snippet in the same file where the main function is. However, the Live Semantic Error feature in Visual Studio says that 'a nonstatic member reference must be relative to a specific object'. In my opinion, the x in function m should be the int x defined in the file-scope and it should be accessible in everywhere of this file.

Please point out where I misunderstood. Thank you in advance!

int x = 0;
class Test1{
protected:
    char *x;
    class Test2{
    public:
        int m(){
            return x++;
        }
    };
};

Upvotes: 3

Views: 1299

Answers (1)

moof2k
moof2k

Reputation: 1897

What you've created here is a nested class: The name of the nested class exists in the scope of the enclosing class, and name lookup from a member function of a nested class visits the scope of the enclosing class after examining the scope of the nested class.

When you refer to x within Test1::Test2::m() in your example, the compiler is going to go up the scope chain and find the first x to be Test1::x. Because this isn't a static member variable you're getting the error.

If you want to refer to the global x use ::x. I modified your example to demonstrate:

#include <stdio.h>

int x = 0;
class Test1{
public:
    char *x;
    class Test2{
    public:
        int m(){
            return ::x++;
        }
    };
};

int main() {
    printf("x = %d\n", x);
    Test1::Test2 foo;
    foo.m();
    printf("x = %d\n", x);
    return 0;
}

This prints:

x = 0
x = 1

$.02 note on style: If you reserve nested classes for simple data containers that only operate on themselves, as is a common best practice, you won't run into this issue.

Upvotes: 2

Related Questions