Laurynas Lazauskas
Laurynas Lazauskas

Reputation: 3251

Why does member variable change, but object's address remains the same in this situation?

In the following code I have an object of class A. I initiate its public member variable with the value of 0. Then I call its method ReplaceThis which executes command *this = A();. Then I print the value and the address of the same object. The value is always some random gibberish while the address remains the same as before ReplaceThis. This confuses me, because unchanged address indicates that the object has not moved in the memory, nevertheless the value changes into some random data even though the constructor of A is empty.

If someone could explain what is going in this code step by step I would greatly appreciate it!

Code:

#include <iostream>

class A
{
public:
    int Data;
    A() {}
    void ReplaceThis() { *this = A(); }
};

int main()
{
    A foo;
    foo.Data = 0;

    std::cout << "Initial  foo data: " << foo.Data << std::endl;
    std::cout << "Initial  foo address: " << &foo << std::endl;

    foo.ReplaceThis();

    std::cout << "Replaced foo data: " << foo.Data << std::endl;
    std::cout << "Replaced foo address: " << &foo << std::endl;
}

Output:

Initial  foo data: 0
Initial  foo address: 0x7fff604594a0
Replaced foo data: 6296256
Replaced foo address: 0x7fff604594a0

Upvotes: 2

Views: 578

Answers (2)

Paul Roub
Paul Roub

Reputation: 36438

We create the object:

A foo;

and set its Data member:

foo.Data = 0;

then, in ReplaceThis():

*this = A();

means:

  1. Create a new object (whose Data will be junk)
  2. Assign that object's value(s) to our object
  3. Nothing changed the address of our object
  4. But we now have the new object's junk Data

Upvotes: 6

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

In this statement

*this = A(); 

there is called implicitly defined by the compiler the copy or move assignment operator. It simply makes memberwise copy of the right hand object. Addresses of the objects are not changed.

Upvotes: 1

Related Questions