Why is 'this' a pointer and not a reference?
In addition to the other answers, since Deducing this is in C++23, it will be possible to have a reference to the object for which a member function is called (instead of this
pointer):
struct Foo {
void bar(this Foo& self) {
// self is a reference to Foo
}
};
int main() {
Foo foo;
foo.bar();
}
A little late to the party... Straight from the horse's mouth, here's what Bjarne Stroustrup has to say (which is essentially repeated in or taken from the "Design and Evolution of C++" book):
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".
When the language was first evolving, in early releases with real users, there were no references, only pointers. References were added when operator overloading was added, as it requires references to work consistently.
One of the uses of this
is for an object to get a pointer to itself. If it was a reference, we'd have to write &this
. On the other hand, when we write an assignment operator we have to return *this
, which would look simpler as return this
. So if you had a blank slate, you could argue it either way. But C++ evolved gradually in response to feedback from a community of users (like most successful things). The value of backward compatibility totally overwhelms the minor advantages/disadvantages stemming from this
being a reference or a pointer.