self = [super init]; // please explain

waiting_for_OSX

Registered
self = [super init];

When placed as the first line in an init method, why does the above line of code not cause a memory leak? I'm coming from a C++ background and I've only studied Obj-C for a few days.
 
Here's how I understand it:

It's assumed that any superclass that will not return the same object will release the previous one. You could omit the "self=" part and it would work MOST of the time, since most of the time all of the init methods in the chain operate on the same object, but that would be messy and inflexible. There are cases when a superclass might pull a switcheroo on you (like with abstract classes and class clusters, such as NSNumber or NSImageRep), and the "self=" accounts for that possibility. This way, in true object-oriented fashion, one object doesn't need to know the details of how any other object works.

So if you wrote a class that for whatever reason needed to return a different object, you could do something like this:
Code:
id result = [[someClass alloc] init];
[self release];
return result;
And the subclass would then operate on "result" just as if it were the original object.

"self" is essentially an invisible argument passed to every selector. Like other arguments, it can be changed within the method, and its scope is limited to that method.
 
Code:
class A
{
public:
  A() {}
};

class B : public A
{
  B() : A()  //call base class constructor
  {
    
  }
};

That's essentially what the Objective-C code you pasted does. It calls the base (or super class in Objective-C parlance) class constructor.
 
Back
Top