0

I have a nested class and I would like it to have access to the attributes of the outer class. I've seen this done on other SO topics (here and some others). However, they always give a reference to an object of the outer class to be able to do that. In my particular case, I would like to avoid using a reference and do it like that:

class OuterClass {
private:
    int _outerData;

public:
    OuterClass(int data) : _outerData(data) {}

    class InnerClass {
    public:
        InnerClass(){
           // Modify or access outerData in the constructor or other methods
           // without using InnerClass(OuterClass& OuterObj)
        }
        //Other methods
    };

I want to do it like that because in my code the user has access to this using a method like this:

OuterClass::InnerClass* OuterClass::NewInnerClass("I don't want to pass any input in here") {
    return new InnerClass("Input here is ok");
}

As you can see, I want the user to call the method without calling any arguments in order to be easier to use.

How can I achieve this type of behavior?

2 Answers2

1

I might be missing something but what's wrong with this

OuterClass::InnerClass* OuterClass::NewInnerClass() {
    return new InnerClass(*this);
}

and this

InnerClass(OuterClass& OuterObj) {
    ...
}

I don't understand why you say

// without using InnerClass(OuterClass& OuterObj)

and

return new InnerClass("Input here is ok");

Those two requirements seem contradictory to me. First you are saying the InnerClass constructor should not have a parameter, and next you are saying that it is OK for the InnerClass constructor call to have arguments.

john
  • 85,011
  • 4
  • 57
  • 81
  • I didn't want argument for my `InnerClass` constructor because I didn't want an argument here: `OuterClass::NewInnerClass()`. And since I dind't know how to do it that's how I expressed my needs. Sorry for the unclear indications. – Unemployed Goose Jul 05 '23 at 07:51
0

InnerClass is a class, not an object. Its only relation to OuterClass is in the name lookup rules, but an instance of InnerClass has no relationship with any instance of OuterClass. For your purposes, the fact that InnerClass is nested doesn't matter. It's just a separate class.

If an instance of InnerClass needs to modify a data member or call an object method of OuterClass, it needs to be told which instance of OuterClass to use.

user1806566
  • 1,078
  • 6
  • 18