Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to enclosing instance from C++ inner class?

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.

like image 588
Tony the Pony Avatar asked Jun 01 '11 08:06

Tony the Pony


People also ask

How do you create an instance of an inner class?

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.

How do you call a static method from an inner class?

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.

Can an inner class method have access to the fields of the enclosing class?

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.

Can inner class calling Outer method?

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.


2 Answers

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.

like image 87
Puppy Avatar answered Sep 22 '22 08:09

Puppy


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;
    };
}; 
like image 32
BЈовић Avatar answered Sep 19 '22 08:09

BЈовић