Copy Assignment Operator
Copy Assignment Operator
The problem is that the assignment of
classObj2 = classObj1;
merely copied the pointer fordataObj
, resulting inclassObj1's dataObj
andclassObj2's dataObj
members both pointing to the same memory location. PrintingclassObj2
prints 9 but for the wrong reason, and ifclassObj1's dataObj
value was later changed,classObj2's dataObj
value would seemingly magically change too. Additionally, destroyingclassObj1
frees thatdataObj's
memory; destroyingclassObj2
then tries to free that same memory, causing a program crash. Furthermore, a memory leak has occurred because neitherdataObj
is pointing at location 81. . The solution is to overload the "=
" operator by defining a new function, known as thecopy assignment operator
or sometimes just theassignment operator
, that copies one class object to another. Such a function is typically defined as:
class MyClass {
public:
...
MyClass& operator=(const MyClass& objToCopy);
...
};
Children