I was reading the answers to this question C++ pros and cons and got this doubt while reading the comments. Why the this is a pointer a not a reference ? Any particular reason for making it a pointer?
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.
For this and other questions on how C++ got to be the way it is, read Stroustrup's excellent book "The Design & Evolution of C++".
A little late to the party... Straight from the horse's mouth, here's what Stroupstrup 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".
Irrespective of how we got here, I think it's lucky that this is a pointer and not a reference as this helps it "make sense" that you can delete it:
void A::f () {
delete &this;
}
I think this is a case where without necessarily being by design, C++ is better as it is.
The C++ standard states that
9.3.2/1
In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
But in other references , it was found something else.. so someone took initiative and shot a mail to Mr. Stroustrup. The conversation that followed can be found here.
Ayush Goyal