TMOTTM
TMOTTM

Reputation: 3381

Why does the address of the assigned object not change in C++?

In this C++ example, a class C has a default constructor, a copy constructor and an assignment operator:

struct C {
    C();
    C(const C& c);
    C& operator=(const C& c);
};

The implementation is as follows with some output for tracking the objects. I added some example addresses in comments on the lines as reference to the main program below.

#include "C.h"
#include <iostream>
using namespace std;

C::C() {
    cout << "Standard constructor." << endl;
}

C::C(const C& c) {
    cout << "Copy constructor." << endl;
}

C& C::operator=(const C& c) {
    cout << "Address of reference argument: &c = " << &c << endl;      // F9B4
    cout << "Address of this: &*this =           " << &*this << endl;  // F8D4
    return *this;
}

I'll be using a factory method that returns anonymous objects:

C foo() {
    return C();
}

Now in the following program, I create a named object c (see (1)) and create an anonymous object (2) which I assign to c (3). I expected that c then has the address of the anonymous object after the assignment.

int main()
{
    C c;  // (1)
    cout << "Address of initial c from main: &c = " << &c << endl;                  // F8D4
    c=foo();  // (2) and (3)
    cout << "Address of initial c from main after assignment: &c = " << &c << endl; // Expected F9B4 but is F8D4
}

Upvotes: 3

Views: 724

Answers (3)

HolyBlackCat
HolyBlackCat

Reputation: 96336

Objects in C++ never change addresses.

An assignment operator is no different from any other method, normally it just goes over all member variables and assigns new values to them, copied from the corresponding members of the other object.

Upvotes: 7

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

The copy assignment operator does not create a new object, It in general changes data members of an already created object. A memory for an object with the automatic or static storage duration is allocated when the object is being created as in this declaration

C c;

Upvotes: 5

Kostas
Kostas

Reputation: 4176

I expected that c then has the address of the anonymous object after the assignment.

Objects in C++ are allocated on the stack, unless explicitly specified by new.

In this case, you're simply creating a temporary anonymous object and then copying it on c. c has the same location on the stack as before.

The reason you might not see the copy constructor message for c=foo(); is because of something called copy elision, which is the reason I assume you thought c would be holding the anonymous object, and not just a copy of it.

Upvotes: 4

Related Questions