Homework 6 — Allocation & Initialization

Due Friday, March 31, 2010

NOTE: The hard copy of this assignment, like others in this class, is due at the beginning of the class period. This means that if you are even a minute late, you lose 20%. If you are worried about potentially being late, turn in your assignment ahead of time. Do this by submitting it to me during office hours or by sliding it under my office door. The electronic copy of this assignment is due at 9:00pm on the due date. Submit the electronic copy using the appropriate dropbox in D2L. Do not send assignments to me through email or leave them in my departmental mail box.

As discussed in class and in your readings, Objective-C has separate messages that can be sent for allocating for objects and initializing those objects.

The assignment.

  1. Rewrite the following Java code in Objective-C.
            Employee newEmployee = new Employee("Bill", "Fenner", "013-14-1155");
  2. The following code is considered unsafe:
            id newThing = [ThingClass alloc];
            [newThing init];
            [newThing doSomething];
    In contrast, the following code is considered safer:
            id newThing = [[ThingClass alloc] init];
            [newThing doSomething];
    Explain what could go wrong with the unsafe code that could not go wrong with the safer code.

  3. Despite the fact that separating allocation and initialization can be unsafe in some circumstances (as seen above), there are situations where we must send an init message to an object for which space has already been allocated. Name one such situation and explain why an init message must be sent to the object in this situation.

What to turn in.

Turn in both printed and electronic copies of your answers.