#Accessing outer class variable from inner class

20 messages · Page 1 of 1 (latest)

empty sand
#

So I've been double checking on nested classes to make sure I'm not going crazy. Given something like

class Outer{
    class Inner{
        int y = 0;

        void changeOuter();
    ];

    int x = 0;
    Inner instance{};
};

I feel like within the changeOuter function I should be able to access the outer class variable without needing to pass a pointer, since firstly, the inner class already knows where it is in memory (with the hidden &self parameter) and secondly knows it's an inner class. But all the examples I see online only mention passing the outer class as a pointer or reference to the inner class methods. Is this still how I'm supposed to do it or am I missing something?

I guess it would have to be static since the inner class doesn't really have a way of knowing if the outer class variable is static or not

With what I'm doing now, my current options are either passing a reference to the outer class to every inner class function or storing a reference to the outer class inside the inner class, which I'm not too fond of in the case of having an array made of the inner class... feels like duplicate data. Would making the inner class's pointer to the outer class a static member mean all instances of every inner class, no matter where, will point to the same outer class (which I also don't want either)?

quaint trenchBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

fading summit
#

an instance of Outer::Inner is not always a member of Outer

#

what happens if i do this?

Outer::Inner foo;
foo.changeOuter();
empty sand
#

Ah, I figured an inner class instance always required an outer class instance to exist

fading summit
#

if Inner instance needs access to int x then you could make x a public member of Inner

#

then Inner and Outer can both access it

empty sand
#

Would have to take out the x from Outer then right?

fading summit
#

ye

empty sand
#

I see... would be useful but I have an array of Inner inside Outer, and the type I'd need access to is only supposed to have one instance

fading summit
#

i was going to say: if the object is a standard layout type and Inner is only ever instantiated as a member of Outer then you can put Inner instance as the first member and cast this to Outer* within changeOuter

#

but if you have more than one Inner per Outer

#

then how would it even know its offset

empty sand
#

I kind of like that, I'll keep that in mind for the future

#

fair...

fading summit
#

this violates law of demeter anyway

empty sand
#

I think I know what I'll do then, thanks!

#

!solved

quaint trenchBOT
#

Thank you and let us know if you have any more questions!

#

[SOLVED] Accessing outer class variable from inner class