Another initializer question


#1

I have another initializer question. This one involves the return value of an initializer…

I know that an initializer is supposed to return a pointer to the object that was initialized. This is normally the object instance for which the initializer was called, but this isn’t guaranteed to be the case.

As an example, lets say I have a class that represents a “house”. I allocate and initialize an object of the class as follows:

House *myHouse = [[House alloc] initWithAddress: @"123 Main Street];

So the inner call to the alloc class method will allocate my house and return a pointer to it. On this returned object, I call the initWithAddress function to initialize my house. Normally the initWithAddress function will return a pointer to the same House object for which the method was called. But it may be possible that the function is smart enough to know that only one house can have a specific address. So, it checks the existing population of House objects and, if it sees one with the address of “123 Main Street”, it frees the House I just allocated and returns a pointer to the already existing House object. This is why we write the alloc / init sequence as above, rather than as:

House *myHouse = [House alloc];
[myHouse init];

This second calling sequence has the potential to allow me to use a House object other than the intended (i.e., already existing) one.

So, now to my question…

When an initializer calls the default initializer of its superclass, the recommended code for the initializer is:

self = [super init];

if (self)
{
// Initialize the derived class’s data members here.
}

return self;

But how can this work for the case where the init method of the superclass returns an object other than the one that the init method was invoked for? In this case, won’t the returned object be an instance of the superclass but not of the derived class? And, thus, won’t the attempts to initialize the derived class’s data members result in some sort of run time errors or exectpions?

Thanks to all for any help here!