Fredrik Johansson
Fredrik Johansson

Reputation: 1301

Ok to skip init method in inherited class?

Consider the following text in http://developer.apple.com/library/ios/#documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html.

Inherited initializers are a concern when you create a subclass. Sometimes a superclass init... method sufficiently initializes instances of your class. But because it is more likely it won’t, you should override the superclass’s initializer. If you don’t, the superclass’s implementation is invoked, and because the superclass knows nothing about your class, your instances may not be correctly initialized.

On the same page I find this text:

Every object that declares instance variables should implement an initializing method—unless the default set-everything-to-zero initialization is sufficient.

My question is: If I skip the init method in class B, where class B inherits from A, can I trust that B's non-inherited member variables are set to zero?

Upvotes: 3

Views: 353

Answers (2)

Caleb
Caleb

Reputation: 124997

My question is: If I skip the init method in class B, where class B inherits from A, can I trust that B's non-inherited member variables are set to zero?

Objective-C will set all ivars of any new object to zero:

The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all, that is, except the isa variable that connects the new instance to its class. For an object to be useful, it generally needs to be more completely initialized. That’s the function of an init method.

So it's okay to skip implementing an initialization method for your class if you don't have any ivars/properties that need to be initialized. You must, of course, still initialize new objects by calling -init or some other initialization method so that the superclass has an opportunity to initialize itself.

Upvotes: 2

DrummerB
DrummerB

Reputation: 40211

Yes, Class B's non-inherited member variables will be zero. Inherited variables will have whatever value is set in Class A's init method (or zero if not set).

Upvotes: 1

Related Questions