Sometimes it just looks like C++ doesn't believe in C++. This is an excellent example. Well, actually this
is. Whenever you're writing a non-static method, you can access the object being acted upon through this
. this
is a pointer to the object. It already comes initialised (because there's no other way of accessing the object, apart from using this
), and you can't change its value. Such objects have a name in C++, but the name is "reference", not "pointer". So why isn't this
a reference?
Let's go back to the favourite example of C++ textbooks: a complex numbers class. Ours will just have a "+" operation defined for it. For convenience, I'll just define operator+=(); it's easy to define operator+() using that (and the default copy constructor):
class Complex {
double re, im;
public:
Complex(double r, double i) : re(r), im(i) {}
Complex& operator+=(const Complex& other) {
re += other.re;
im += other.im;
return *this;
}
}
This is almost the only way to use
this
; had
this
been
Complex&
instead of
Complex*
the only difference would have been
return this;
, which is surely clearer.
As it stands, this
behaves like a reference, not like a pointer. It's not even like a constant pointer: that can be NULL (or , as we say in C++), but this
is guaranteed to refer to a valid object. So why on earth isn't it a reference?
Because C++ doesn't believe in C++!