Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a reference to 'this' in the constructor

Tags:

c#

constructor

I know I have done this before but I am getting my constructor order of execution in a twist I think....

public class Class1
{
    Class2 _class2;

    public Class1()
    {
        _class2 = new Class2(this);
    }
}

public class Class2 
{
    Class1 _parent; //corrected typo

    public Class2(Class1 parent)
    {
        _parent = parent;
    }
}

trouble is that parent always ends up null.

What's the proper way to do this? (maybe I can blame my slowness on having a cold..)

EDITED TO CORRECT THE TYPO (which isn't the problem in the real code!)

like image 243
kpollock Avatar asked Apr 09 '09 15:04

kpollock


People also ask

Can you pass this in constructor C++?

The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object.

Can this be passed as an argument to constructor?

You can pass an argument of any data type into a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as classes and arrays.

How do you pass a constructor in Java?

Constructors can be passed as arugments to methods using a method reference, somewhat like a function pointer in C++. This can be a Function type with one argument or a BiFunction type with two arguments, either way its a lambda returning a class of the type it constructs.


1 Answers

This should, technically, work, provided you change Class2 to include this.parent = parent;

However, I don't recommend this. I would, instead, recommend lazy initializing your class2 instance inside class1. Depending on what all is done in the constructor of Class2, you can potentially lead yourself into nasty situations.

Making a Class2 property on class1 and lazy initializing it would cause Class2 to be constructed after Class1's constructor is completed, not during it's construction, which is most likely less error prone if your classes get more complicated.

like image 111
Reed Copsey Avatar answered Sep 17 '22 20:09

Reed Copsey