c++inner-classesthis-pointer

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.


Solution

  • 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