c++pointersthis

C++ this pointer


I am trying to learn the basics of C++ from an elementary book. I am trying to solve this question... "If there are four objects in a program, how many "this" pointers would exist for these objects and why?"

My initial instinct was that there is only one "this" pointer and it points to the object whose member function calls the "this" pointer. But there was no basis for my answer and so I tried to verify it. I thought if there are multiple this pointers in a program, they would all be saved at different locations in memory. If there is only one, the address of the "this" pointer would always remain the same. So I wrote the following program and ran into an lvalue error.

#include <iostream>
#include <cstring>
using namespace std;

class person
{
    char name [10];
    int age;
    public:
    
    person () {}
    
    person (const char *s, int a)
    {
        strcpy (name, s);
        age = a;
    }
    
    void display (void)
    {
       cout << "Address of this pointer is " << &this << endl;
    }
};

int main()
{
    person A ("Jimmy", 12), B ("Joe", 44);
    A. display ();
    B. display ();
    return 0;
}

Can you please suggest corrections to the above program or any other way to do it?


Solution

  • There are a few things that we know about this : it exists inside member functions of classes (except static members), and it is used to refer to a specific instance of that class (i.e. an object). It's an expression without an address. (Common enough, the number 3 is also an expression without an address).

    What we don't know about this is what happens to it outside a member function. Does the compiler bother to store it? Often, there's no need to. If you have std::array<person, 500> A, then the compiler can easily calculate the this pointer that's needed to call A[42].display(). The compiler will derive it from the this pointer of A itself. But at other times, the compiler can store it.

    And if you don't actually use this in a member function (not even implicitly, to access members), the optimizer may decide to remove the unnecessary calculation.

    Hence, the answer depends on the exact compiler, compiler settings and the exact point in your program.