Question

I got two classes.

  • busiObj(created from ancient flat files)
  • key(provides means to tell busiObjs apart)

key has a c'tor that takes a busiObj

public key(busiObj foo)
{
    bar = foo.someThing;
    [...]
}

I want to create the key in the c'tor of the busiObj

public busiObj(...)
{
    myKey = new key(this);
    [...]
}

However: Why on earth does it work?
I firmly expected the compiler to throw something like:
"You cannot reference an object that is currently being made, duh".

So: How is it that I can reference an object while it is still being constructed?

Was it helpful?

Solution

So: How is it that I can reference an object while it is still being constructed?

Presumably Because it's useful (though in a dangerous way) for exactly the scenario you describe, so the language designers decided to allow it.

Technically, it's not a problem at all: while the object is being constructed, its memory must already be allocated, so you can certainly have a reference to it.

OTHER TIPS

Why this happens is because this is a reference to the memory area that your object is currently occupying. Since instructions in the code are executed sequentially, you already have your object in some state that's being referenced when you get to the point of calling the key() method.

Although this is possible, the entire approach is wrong. The methods inside an object should only change the state of the instance, not the state of other instances of that object. Your example works because it roughly translates into the code below at runtime:

public busiObj() { 
    myKey = new key();
    [...]
}

public key()
{
    bar = foo.someThing;
    [... use "this" here to reference your object internally ...]
    [... other stuff here ...]
}
Licensed under: CC-BY-SA with attribution
scroll top