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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With