12

Possible Duplicates:
Why ‘this’ is a pointer and not a reference?
SAFE Pointer to a pointer (well reference to a reference) in C#

The this keyword in C++ gets a pointer to the object I currently am.

My question is why is the type of this a pointer type and not a reference type. Are there any conditions under which the this keyword would be NULL?

My immediate thought would be in a static function, but Visual C++ at least is smart enough to spot this and report static member functions do not have 'this' pointers. Is this in the standard?

Community
  • 1
  • 1
davetapley
  • 17,000
  • 12
  • 60
  • 86
  • 2
    Dupe http://stackoverflow.com/questions/645994/why-this-is-a-pointer-and-not-a-reference –  Feb 11 '10 at 18:30
  • 2
    Not and exact duplicate! The other question does not address the secondary questions posed here, like "can `this` ever be null?". I was in the middle of answering that when this question was closed. – Adrian McCarthy Feb 11 '10 at 18:58
  • 1
    On the question of whether `this` can be null, the answer is no, not in a well formed program. – David Rodríguez - dribeas Feb 11 '10 at 20:25
  • 1
    In practice, null `this` happens. If you have a pointer to an object, and the pointer is null, and you try to call a method (e.g., `p->method()`), you'll often crash in the method because `this` is `NULL`. I'm sure there are variations by compiler. But `this` will never be null in a correct program. – Adrian McCarthy Feb 11 '10 at 20:41

3 Answers3

17

See Stroustrup's Why is this not a reference

Because "this" was introduced into C++ (really into C with Classes) before references were added. Also, I chose "this" to follow Simula usage, rather than the (later) Smalltalk use of "self".

manuelz
  • 142
  • 4
Dario
  • 48,658
  • 8
  • 97
  • 130
  • 2
    Why the downvote ? , this comes from BS (apparently) – Tom Feb 11 '10 at 18:35
  • Maybe someone thought I copied the answer from the duplicate question (which is not the case, I've just discovered it in this second). – Dario Feb 11 '10 at 19:03
3

Because references weren't added to C++ until later. By then it was too late to change it.

rlbond
  • 65,341
  • 56
  • 178
  • 228
0

(probably not a complete answer) There is always the situation when an object needs to delete itself with the "dangerous"

delete this;

So it probably have to be a pointer.

M.

Max
  • 3,128
  • 1
  • 24
  • 24
  • 7
    If it were a reference you could `delete &this;`. – Jon-Eric Feb 11 '10 at 18:33
  • 2
    `delete &this` might even have an advantage over `delete this` in that the additional `&` might make you ask yourself if you're actually allowed to delete the current object, ie. if it was dynamically allocated on the heap. `delete this` looks much more unobtrusive in this respect, IMO. – stakx - no longer contributing Feb 11 '10 at 18:34