The size of a class with no data members is returned as 1 byte, even though there is an implicit ‘this’ pointer declared. Shouldn’t the size returned be 4 bytes(on a 32 bit machine)? I came across articles which indicated that ‘this’ pointer is not counted for calculating the size of the object. But I am unable to understand the reason for this.
Also, if any member function is declared virtual, the size of the class is now returned as 4 bytes. This means that the vptr is counted for calculating the size of the object. Why is the vptr considered and ‘this’ pointer ignored for calculating the size of object?
The size of a class with no data members is returned as 1 byte,
Share
The
thispointer is not a member of the class. It’s just a construct that is used in methods belonging to the class to refer to the current instance.If you have a class like this:
This class only needs space for two instances of
intfor each instance. Once you’ve created an instance and are running thesum()method, that method is called with a pointer to the instance, but that pointer always comes from somewhere else, it isn’t stored in the object instance.For example:
Notice how the variable that becomes the
thispointer is stored outside the object, in the scope that created it.You could, in fact, always transform a method like the one above into:
If the above is defined inside the class (so it can access the private members), there’s no difference. In fact, this is how methods are implemented behind the scene; the
thispointer is just a hidden argument to all member methods.The call would become: