Search code examples
c++classpointersthismemory-address

"this" pointer in parameterized constructor points to another address than from outside


I have the following code:

#include <iostream>

class Entity {

public:
    int x;
    int y;

    Entity() {
        std::cout << "Default contructor: " << this << std::endl;
    }

    Entity(int x, int y) {
        this->x = x;
        this->y = y;

        std::cout << "Constructor with parameter: " << this << std::endl;
    }
};

int main()
{
    Entity e;
    e = Entity(10, 20);

    std::cout << "Adress from outside: " << &e << std::endl;

    std::cin.get();

    return 0;
}

Why is the address in the main fuction the same as the address in the default constructor? And is there any way to get access to the memory address of the object initialized with parameters from main?


Solution

  • Why is the address in the main fuction the same as the address in the default constructor?

    Because e is the same object, always. You cannot move it in memory or anything like that. It will occupy the same memory spot until it dies.
    What you are using in e = Entity(10, 20); is called move assignment operator. Note that despite the name, nothing is actually moved, because it cannot do that. Default compiler generated move assignment operator simply calls move assignment on each of the class members (and move assignment for ints is equivalent to a copy).

    And is there any way to get access to the memory address of the object initialized with parameters from main?

    No. That object was a temporary and it is gone after the semicolon finishing this line. You would need to give it a name to keep it as another variable.