4

How can I access class attribute from its nested class method?

class Class1
{
public:
    int attribute;
    void Method1() { 
        class Class2
        {
            public:
               void Method2() { 
                   //here I need to access attribute from Class1
               }
        };
    }
};
7
  • possible duplicate of struct in class Commented Apr 8, 2013 at 18:32
  • 1
    I would just pass this either as a method parameter or when constructing Class2. Commented Apr 8, 2013 at 18:34
  • @refp: The link you suggested is a bit different. Commented Apr 8, 2013 at 18:34
  • Inside Class2::Method2(), you would need some global accessor funciton to find Class1's this so you could then access its public attribute. Or, you can pass Class1's this to Class2 as part of Class2's construtor so it knows who its parent is so that it can access Class1's public attributes. Commented Apr 8, 2013 at 18:35
  • @MM. it boils down to the same thing. Commented Apr 8, 2013 at 18:35

2 Answers 2

2

Following is one way of doing it with minor changes to OP's code.

#include <cassert>

class Class1
{
    public:
        Class1( int attribute ) : attribute_( attribute ) {
        }
        void Method1() { 
            class Class2
            {
                public:
                    Class2( Class1 * parent ) : parent_( parent ) {
                    }
                    int parentAttribute() const { 
                        return parent_->attribute_;
                    }
                private:
                    Class1 * parent_;
            };
            Class2 c2( this );
            assert( c2.parentAttribute() == attribute_ );
        }
    private:
        int attribute_;
};

int main() {
    Class1 c1( 42 );;
    c1.Method1();
}

The code is also posted at http://codepad.org/MUF3a8jL

Sign up to request clarification or add additional context in comments.

1 Comment

@MM. Thanks! I never did this before, this is something I learned today :-)
2

You can pass this to the inner class. For example:

class Class1
{
public:
    Class1() : class2(this) {
    }

    int attribute;
    void Method1() { 
    };

    class Class2
    {
        Class1 *parent;
    public:
        Class2(Class1 *parent) : parent(parent) {
        }
        void Method2() { 
             // parent->attribute
        }
   } class2;
};

4 Comments

It isn't shown nor specified that Class2 will always be used by Class1. Without that specification, there is no need for Class1 to always initialize Class2 on Class1's construction.
But the two approaches are quite different things. no?
Why can not I declare a class with methods inside another method? I did and it works
It's just a sample to how call parent's method. He can do it with temporary Class2 object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.