Copy Assignment Operator
Copy Assignment Operator
The problem is that the assignment of
classObj2 = classObj1;merely copied the pointer fordataObj, resulting inclassObj1's dataObjandclassObj2's dataObjmembers both pointing to the same memory location. PrintingclassObj2prints 9 but for the wrong reason, and ifclassObj1's dataObjvalue was later changed,classObj2's dataObjvalue would seemingly magically change too. Additionally, destroyingclassObj1frees thatdataObj'smemory; destroyingclassObj2then tries to free that same memory, causing a program crash. Furthermore, a memory leak has occurred because neitherdataObjis pointing at location 81. . The solution is to overload the "=" operator by defining a new function, known as thecopy assignment operatoror 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