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
...
}
You assign an object to such a variable by placing the object after the equal sign ( = ) in an assignment statement or initialization clause.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With