can someone tell the difference between objective C's self and C++ this pointer?
-
What do your Objective-C and C++ references tell you? – GManNickG Sep 28 '10 at 08:13
-
possible duplicate of [Assigning to self in Objective-C](http://stackoverflow.com/questions/1341734/assigning-to-self-in-objective-c) – Kirill V. Lyadvinsky Sep 28 '10 at 08:29
-
3Kirill V. Lyadvinsky: It's not a duplicate of that question. The questioner there already understood the answer to this question. – JeremyP Sep 28 '10 at 08:32
2 Answers
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.
-
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 Sep 28 '10 at 08:43
-
@jv42: my compiler doesn't allow that without setting an option, so I assumed it was either non-standard or anachronistic. – Sep 28 '10 at 08:56
-
1
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.

- 84,577
- 15
- 123
- 161
-
-
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 Sep 28 '10 at 11:10