Where is the 'this' pointer stored in computer memory?

nagaradderKantesh picture nagaradderKantesh · May 16, 2013 · Viewed 11k times · Source

Where exactly is the 'this' pointer stored in memory? Is it allocated on the stack, in the heap, or in the data segment?

#include <iostream>
using namespace std;

class ClassA
{
    int a, b;

    public:
        void add()
        {
            a = 10;
            b = 20;
            cout << a << b << endl;
        }
};

int main()
{
    ClassA obj;
    obj.add();
    return 0;
}

In the above code I am calling the member function add() and the receiver object is passed implicitly as the 'this' pointer. Where is this stored in memory?

Answer

unwind picture unwind · May 16, 2013

The easiest way is to think of this as being a hidden extra argument that is always passed automatically.

So, a fictional method like:

size_t String::length(void) const
{
  return strlen(m_string);
}

is actually more like this under the hood:

size_t String__length(const String *this)
{
  return strlen(this->m_string);
}

and a call like:

{
  String example("hello");
  cout << example.length();
}

becomes something like:

cout << String__length(&example);

Note that the above transformation is simplified, hopefully to make my point a bit clearer. No need to fill up the comments with "whaaa, where's the marshalling for method overloading, huh?"-type objection, please. :)

That transforms the question into "where are arguments stored?", and the answer is of course "it depends". :)

It's often on the stack, but it could be in registers too, or any other mechanism that the compiler considers is good for the target architecture.