Jump to content

This (computer programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by EngineerScotty (talk | contribs) at 18:56, 30 January 2006 (initial rev). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In many object-oriented programming languages, this (or self) is a keyword which is used to refer to the object on which the currently executing method has been invoked. C++, and programming languages which derive from it (such as Java and C#) generally use the keyword this, whereas Smalltalk and it's progeny prefer the keyword self. The Self programming language is named after this use of "self".

In all of the above languages, this/self is an immutable reference (a pointer in C++) which refers to the current object. It is generally guaranteed to be a valid reference (it is never the null pointer). Some languages require it's use to refer to the current object; other languages uses lexical scoping to make symbols defined within the corresponding class definition visible, making use of this unnecessary in some instances.

This and C++

Early dialects of C++ were unusual in that they permitted the this pointer to be modified; in this way a method could "switch" which object it was working on. This feature was eventually deprecated, and this in C++ may not be rebound. (Early versions of C++ did not include references; had references been included in the language it is likely that this would have been of reference rather than pointer type--as the semantics of this in C++ far more resemble references than pointers).

C++ does permit objects to "commit suicide" with the construct delete this; this operation, when performed, invalidates the object (and the this pointer). Some C++ authors now consider "delete this" to be a dangerous construct and advise against its use.

  • The Design and Evolution of C++ by Bjarne Stroustrup - Addison-Wesley Pub Co; 1st edition (March 29, 1994); ISBN 0201543303
  • More Effective C++: 35 New Ways to Improve Your Programs and Designs by Scott Meyers -- (1995) ISBN 020163371X