views:

94

answers:

2

can someone tell the difference between objective C's self and C++ this pointer?

+4  A: 

Yes. One is spelt s-e-l-f. The other is spelt t-h-i-s.

Less facetiously:

self is used in Objective-C classes to represent a pointer the current instance.

this is used in C++ classes to represent a pointer the current instance.

They perform analogous roles but on entirely different structures.

JeremyP
@Preet Sangha: And what is wrong with having a joke in the answer?
JeremyP
Lol. I wrote joke because I was too lazy to look up how to spell facetiously once I'd removed it. And to answer your question nothing at all.
Preet Sangha
+5  A: 

The main difference is that this is a keyword, while self is a variable. The result of this is that while this always refers to the object that is executing a particular method, Objective-C methods are free to modify self during execution. This is sometimes used by constructors, which set self = nil on failure.

The reasons for doing so are:

  • so that subclasses (which chain initialisers with self = [super init]) can see when the initialisation fails and know not to carry on in their own initialisers.
  • composing objects can see the failure and know that they don't have a valid component.

Some initialisers will set self to a different, but valid, object. This can be used in class clusters, where the "abstract" class can generate a temporary instance while building the initialised object, but ultimately return a different object based on the properties that were built up during construction.

In addition, it means that you can do the usual things with variable names that confuse everyone that you can't do with keywords, such as defining a more local variable with the same name self in a code block.

Graham Lee
In C++, you *can* modify the value of this. Not saying that you should, but I've seen it used to pack some extra info on a system where 32 bits pointer wasn't fully used by memory mappings...
jv42
@jv42: my compiler doesn't allow that without setting an option, so I assumed it was either non-standard or anachronistic.
Graham Lee
@jv42: `this` is an rvalue, it cannot be modified.
GMan