user8577930
user8577930

Reputation: 193

How would you the "this" pointer of the base class from a method of a nested class?

I have a class nested in a base class, like so:

class Base {
public:
    void methodB() { std::cout << "method B"; }
    class Nested {
    public:
        void methodA() { methodB(); }
    };
    Nested * member;
};

This obviously generates a compiler error:

Cannot call member function methodB without object

because methodB is not declared as static. This will be ok in main, because methodB will be called by doing instanceOfBase.member->methodA(), which will in turn call methodB, but the problem I'm encountering is that I don't know how to access the underlying this pointer to instanceOfBase from its member object.

Upvotes: 1

Views: 189

Answers (2)

eerorika
eerorika

Reputation: 238401

base class ...

"Base" class means something else. You're asking about an outer class.

methodB will be called by doing instanceOfBase.member->methodA(), which will in turn call methodB, but the problem I'm encountering is that I don't know how to access the underlying this pointer to instanceOfBase from its member object.

There is no "underlying" this pointer to instanceOfBase. The structure looks like this:

Base ---> Nested
      ^
      |
      pointer

"Base" doesn't contain any Nested object, but it does point to one. Nested doesn't contain any "Base" objects, nor does it point to one. Since it is not associated with any "Base", there is no way to access such "Base" object from Nested one.

One solution is to provide a wrapper function in "Base" that passes the instance to the pointed Nested object:

class Base {
public:
    // ...
    void methodA() {
        member->methodA(*this);
    }
};
// usage
instanceOfBase.methodA();

Upvotes: 2

Miles Budnek
Miles Budnek

Reputation: 30579

An object of a nested class isn't inhanently linked to an object of the class it's definition is nested in. Consider something like this:

Base::Nested{}.methodA()

What Base object would that operate on?

If you have some invariant that objects of Nested are always contained in Base objects, then you have to maintain that link. For example, you could pass your Base object's this pointer to the Nested object's constructor in Base's constructor:

class Base {
public:
    class Nested {
    public:
        Nested(Base* owner) : owner{owner} {}
        void methodA() { owner->methodB(); }
        Base* owner;
    };

    Base() : member{this} {}
    void methodB() { std::cout << "method B"; }

    Nested member;
};

Live Demo

Upvotes: 2

Related Questions