In C++ why isn't this a reference?

| 5 Comments

In C++ every object has a "this" pointer. You could think of it as being passed as an implicit argument to every non static member function that the object has. It can never be null so why isn't it a reference?

The reason I started wondering about this is that when using wiring objects together, such as when using parameterise from above, I often find myself wanting to pass a reference to the current class to some related object. More often than not I actually want to pass a reference and not a pointer, because the relationship is not optional and the pointer can never be null. Because this is a pointer my code ends up littered with pointer dereferencing *'s to convert this from CFoo * to CFoo & like this WireMeUp(*this)...

5 Comments

The best answer I saw was at everything2, read all the replies at: http://www.everything2.com/index.pl?node=C++: What's this? A reference?"

I'm sure this is commented on by Stroustrup in Design and Evolution - that it should be a reference but references were added to the language much later than 'this' and he didn't want to break backwards-compatibility.

I had a quick look in the ARM but couldnt see anything, I'd forgotten D&E... It's covered on page 39 and is for the reasons you point out.

Actually, I get null 'this' from time to time; its always an error in the caller: call a non-virtual member with a null pointer ((atype*)0)->afun();

Leave a comment