The This Pointer in C++

2017-02 Update

I didn’t know about boxing and unboxing of primitives to objects (or much about references as it happens) when I wrote this back in 2013. Primitives like int/bool/float/char/double etc. DO get copied via the default copy constructor because they have default working copy/assignment functions. However if the Example class held an instance of, say, a DeepCopyWang object (it was the first thing I could think of) – it wouldn’t copy cleanly with the default assignment or copy constructors – any new object would just hold a reference to the original DeepCopyWang object and its properties. That is, the new object trying to be a copy of the first would be a shallow copy (i.e. it may contain references to properties of the first object) and not a deep copy (i.e. completely separate objects and all properties there-in which can be individually manipulated). So take the below with a suitably sized pinch of salt.

Still on my fundamentals trip, I’m hitting up the ‘this’ pointer. Every class that you create has a ‘this’ pointer invisibly assigned to it by the compiler. Let’s look at a simple class to see what’s going on:

When you write the above code the compiler does some fun things with it, such as invisibly adding four methods:

  • A default constructor (that takes no parameters) which is automatically executed when you instantiate an object of this type,
  • A destructor (again no parameters) which is automatically executed when an object of this type is deleted or goes out of scope,
  • A copy constructor (that takes another object of this type) and performs a shallow copy from the source object to the (new) destination object, and
  • An assignment operator (that takes another object of this type) and which again performs a shallow copy from that object the the object you’re assigning to.

If we explicitly write these four methods into our class, we end up with our (exactly, exactly equivalent) code now being:

You can substitute either of these classes into a project, compile it (in Release mode if you have both in there and just comment each out in turn!), and you’ll end up with byte-wise identical executables down to the very last bit. Not only are they functionally equivalent, they’re absolutely equivalent – as the compiler sees them, it’s the exact same code. Don’t take my word for it – try it out, if you’d like!

The ‘this’ pointer’s already being used, but what exactly is it doing? Well, let’s drill down into the nuts and bolts of it and take a look…

Continue reading The This Pointer in C++