Amazon.com Widgets overriding init
Welcome, Guest. Please login or register.
Did you miss your activation email?
May 24, 2013, 02:47:19 PM
Home Help Search chat Login Register   
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+  Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+  Programming in Objective-C, 4th edition
| |-+  Chapter 10
| | |-+  overriding init
Pages: [1]   Go Down
Print
Author Topic: overriding init  (Read 197 times)
littfam
Newbie
*
Posts: 8


Email




« on: October 30, 2012, 06:48:48 PM »

on page 196 it reads "If the parent's initialization succeeds, the value returned will be non-nil as tested by the if statement".  My question is,  why will it return a non zero value?  I should probably know this by now, but the reason is eluding me for some reason.  

Edit:  Got answer over at S.O.  Will leave for posterity.

Answer:

Consider the following scenario, you have a parent class, which we'll call Parent, that has the following layout:

@implementation Parent {
    int value;
}
and you have a class Child, which is a subclass of Parent, and has the following layout:

@implementation Child {
    int other;
}
within the Child subclass, you have no direct access to the Parent ivar called value. However, in its initialization, Parent assigns some integer to value, and some functionality in Parent depends on this value being set.

if Child does not call [super init], value will never be initialized and part of the functionality of Parent, which Child inherits, will be broken. The init method is defined to return a pointer to the initialized object instance. If you ignore the return value of [super init], you can get into trouble, because the parent init may have decided to reassign the object instance to some location other than the one provided by the allocator.

For instance, NSString can detect initialization with empty string literals, and will return a pointer to a constant NSString reference instead of one on the heap. So say you just call [super init] and ignore its return value, and keep using the self pointer value passed to the Childs init method, you're suddenly using a dangling pointer!

This is an extreme case, but the point is, if you intent to inherit functionality from your parent class, you should assign self to [super init], and you should check if it returns nil because it may have decided to fail initialization and destroy the memory provided to it by the allocator.
« Last Edit: November 01, 2012, 07:50:57 PM by littfam » Logged
Pages: [1]   Go Up
Print
Jump to:  



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.