RK-
RK-

Reputation: 12211

Difference b/w Objective C's self and C++'s this?

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

Upvotes: 10

Views: 11465

Answers (2)

user23743
user23743

Reputation:

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.

Upvotes: 23

JeremyP
JeremyP

Reputation: 86651

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.

Upvotes: 6

Related Questions