I have heard that when you have a subclass, you are supposed to initialize the superclass with the same init function from within the subclass’s init. What I mean is that the subclass’s init should call [super init] and the subclass’s initWithFrame should call [super initWithFrame]. Why is this? Why does calling the super’s init from a subclass’s initWithFrame result in an infinite loop?
If this is required, then does this mean I can’t create a new init function within a subclass such as initWithPoint and have that call super’s init or initWithFrame simply because the super class doesn’t have initWithPoint? I guess the heart of the question here is simply why it’s improper to call a different super class, something that’s confusing me possibly because of my c++ background?
When you create a subclass, if you implement an initializer, then you must be sure to call the superclass’s designated initializer(s), and you must provide at least one designated initializer of your own, though this can just be your override of the superclass’s.
As part of initializing your subclass, you must call one of the superclass’s designated initializers.
A class’s documentation should nominate its designated initializers. If not, the designated initializer is generally assumed to be the most specific initializer (the one taking the most arguments) provided by the superclass.
For further details, see “The Objective-C Programming Language: Allocating and Initializing Objects.” [Note: As of December 2013, this content no longer appears to be available via Apple’s doc center. What was a language reference has been replaced by more task-oriented tutorials and conceptual documentation.]
As to your specific questions:
Why is this? So that the superclass has a chance to initialize its state. You can then go ahead and initialize the state you add above and beyond what the superclass provides.
Why does calling the super’s init from a subclass’s initWithFrame result in an infinite loop? Because, for
NSView,-initis not the designated initializer, though it isNSObject‘s. SoNSViewoverrides it to call its designated initializer,-initWithFrame:. If you’ve called-initfrom your-initWithFrame:, you now have-initWithFrame:calling-initcalling-initWithFrame:calling-init:calling…Does this mean…? No, because this is not required. You must understand the actual documentation, not hearsay.