genibec746
genibec746

Reputation: 41

nested class invalid use of non static data member

Hi i need help with this little example. I am unable to use _test from the nested class

class random
{
public:
    int _test;

    class nestedClass
    {
    public:
        void notify() override {
            _test = 123;
        }
    } _nestedClass;
};

Upvotes: 0

Views: 1225

Answers (2)

Todd Wong
Todd Wong

Reputation: 234

You can't access the non-static member of random without a instance of random. You need to tell your nestedClass which _test it want to access. There may be many instances of random out there, and therefor, many _tests.

I think what you want is:

class random
{

public:
    int _test;

    class nestedClass
    {
        random& outer_;
    public:
        nestedClass(random& outer): outer_(outer) {
        }
        void notify() {
            outer_._test = 123;
        }
    } _nestedClass;
    
    random(): _nestedClass(*this) {
    }
};

Upvotes: 1

user12002570
user12002570

Reputation: 1

You can use/pass a pointer to the outer class named random to achieve what you want as follows:

void notify(random* p) 
{
    p->_test = 123;
}

This is because a nested class can access a non-static member of the enclosing class through a pointer to the enclosing class.

You can also pass arguments as:

void notify(random* p, int i) 
{
    p->_test = i;
}

Upvotes: 1

Related Questions