Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When object variable is reassigned in C++, what happens to the original object?

When an object variable is reassigned in C++, what happens to the original value? In the code below an object is created onto the stack and placed in variable. Then a new object is created on the stack and placed in the same variable. What happens to the original object? Does it stay on the stack until variable goes out of scope?

void foo() {
    ClassName variable(a, b); // variable created on the stack
    variable = ClassName(c, d); // new value for variable created on stack
    ...
}
like image 554
naavis Avatar asked Dec 15 '14 22:12

naavis


People also ask

Can a variable be assigned to an object?

You assign an object to such a variable by placing the object after the equal sign ( = ) in an assignment statement or initialization clause.

What happens when we assign one object to another in C++?

Assignment of one object to another simply makes the data in those objects identical. The two objects are still completely separate. Thus, a subsequent modification of one object's data has no effect on that of the other.

Can you reassign an object in C++?

As you know, an address of an object in C++ can be stored either through a reference or through a pointer. Although it might appear that they represent similar concepts, one of the important differences is that you can reassign a pointer to point to a different address, but you cannot do this with a reference.


1 Answers

What happens is that the class's assignment operator is called. In most cases that just means that the contents of the old object are updated with values from the new object. So if ClassName is:

struct ClassName
{
    int a;
    int b;

    ClassName(int a, int b) : a(a), b(b) {}
};

In this case the default assignment operator would be called which would be equivalent to:

    ClassName& operator=(const ClassName& other)
    {
        a = other.a;
        b = other.b;
        return *this;
    }

For classes that have dynamic content there would be a bit more to do, but the results will generally be the same. Since the assignment operator can be overridden, anything could theoretically happen but this is what we expect.

like image 164
Jay Miller Avatar answered Oct 21 '22 23:10

Jay Miller