In C++, an object refers to itself via this
.
But how does an instance of an inner class refer to the instance of its enclosing class?
class Zoo
{
class Bear
{
void runAway()
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
??? /* I need a pointer to the Bear's Zoo here */);
}
};
};
EDIT
My understanding of how non-static inner classes work is that Bear
can access the members of its Zoo
, therefore it has an implicit pointer to Zoo
. I don't want to access the members in this case; I'm trying to get that implicit pointer.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.
InnerClass inn = out. new InnerClass(); Then You can call any method in innerClass from this object. This will qualify the enclosing classes to be Inner classes.
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
No, you cannot assume that the outer class holds an instance of the inner class; but that's irrelevant to the question. You're first question (whether the inner class holds an instance of the outer class) was the relevant question; but the answer is yes, always.
Inner classes are not special, and don't have any link to their outer class built-in. If you want to access the outer class, then pass a pointer or reference, just as you would with any other class.
Unlike Java, inner classes in C++ do not have an implicit reference to an instance of their enclosing class.
You can simulate this by passing an instance, there are two ways :
pass to the method :
class Zoo
{
class Bear
{
void runAway( Zoo & zoo)
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
zoo );
}
};
};
pass to the constructor :
class Zoo
{
class Bear
{
Bear( Zoo & zoo_ ) : zoo( zoo_ ) {}
void runAway()
{
EscapeService::helpEscapeFrom (
this, /* the Bear */
zoo );
}
Zoo & zoo;
};
};
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