SolidMechanicsFan
SolidMechanicsFan

Reputation: 325

how to get a reference to the instance which created 'this'?

#include <iostream>

struct Class1 {
    Class1(int var1_);
    int var1;
};

Class1::Class1(int var1_)
    : var1(var1_)
{
    //how to get a referecnce to the instance of class2 ???
}

struct Class2 {
    Class1 instance1;
    Class2(int var);
};

Class2::Class2(int var)
    : instance1(Class1(var))
{
}

int main()
{
    Class2 instance2(3);
}

In the main function I create a instance of Class2. Class2 has a member from Class1, so the consructor of Class2 calls the constructor of Class1.

Inside the constructor of Class1 I would like to get a reference to the instance of Class1, i.e. the instance which created the instance of Class2. How can one achieve that without passing the address to the constructor? 'this' would refer to the just created Class2 instance and not to the Class1 instance which caused the creation of the Class2 instance. Any Input is appreciated! :)

Upvotes: 0

Views: 281

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148880

You cannot.

Only the pointer to the current object is implicitely passed in this. Any other element has to be explicitely passed. The constructor Class1::Class1(int var1_) cannot have a hidden reference to a Class 2 object, because it could have been created outside a Class2 context.

If you want to be able to use a reference to the Class2 object, you must pass it explicitely:

Class1::Class1(int var1_, Class2& parent);

and later:

Class2::Class2(int var): instance1(Class1(var, *this))

But beware: inside Class1 ctor, you can store the address of the Class2 object, but not use it because it is not yet fully constructed.

Upvotes: 2

Related Questions