Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" keyword in C++ nested classes

If I have the following nested classes:

class foo {
public:
    class bar {
    public:
        int barMethod() const;
    protected:
        int barVar;
    };

protected:
    int fooVar;
};

and then in a .cpp, can I implement barMethod() this way?

int foo::bar::barMethod() const {
    return this->fooVar + this->barVar;
}

What I mean is: does this keyword in a nested class refer to all classes that are upstream in hierarchy?

like image 376
Benjamin Barrois Avatar asked Mar 06 '23 07:03

Benjamin Barrois


1 Answers

does this keyword in a nested class refer to all classes that are upstream in hierarchy?

No, "current" class only. Class nesting is mostly a lexical thing. Unlike in, say, Java, where an inner class can be associated with an instance of an enclosing outer class, foo::bar is pretty much like any other class that isn't nested.

If you want to associate an instance of bar with an instance of foo, you need to capture a reference or a pointer to foo in bar.

like image 193
StoryTeller - Unslander Monica Avatar answered Mar 15 '23 09:03

StoryTeller - Unslander Monica