+ 1

How to overload assignment operator for a class having member as " int * ptr; and A *a;" Here A is class declared in some librar

How to write assignment operator overload function for a class like class Demo { int *ptr; A *a; }; Here A is class declared in some library. I can do like Demo& operator=(const Demo& obj) { if(this != Obj) this->ptr = obj.ptr; (For class A pointer *a how i will do i am not sure) } Can someone please help me with this and give me one working function.

14th Oct 2019, 1:38 PM
Amit chavare
Amit chavare - avatar
4 odpowiedzi
+ 2
Depends, do you want a shallow or a deep copy? If a shallow copy is enough, you can simply do the assignment, just like with ptr: this->a = obj.a; You can always assign pointers pointing towards the same type to each other, but note that if you do that, they will both point to the same object afterwards, not to two different, independant objects, because only the address is copied over. If you expect two independant objects from copying such a class, you will have to use dynamic memory allocation, and you will not only need a copy constructor, but also an overloaded assignment operator and a destructor.
14th Oct 2019, 2:12 PM
Shadow
Shadow - avatar
+ 2
Here is an example of shallow copying: https://code.sololearn.com/cnKFm0atK6MG/?ref=app Versus a deep copy: https://code.sololearn.com/cKlcE0u8rZsx/?ref=app As you see, for a deep copy, dynamic memory allocation is used, so that each object has its own pointer, which points to its own independant object. Upon copying, the old object is deleted and a new one is allocated (you could also assign the fields one by one, but usually this is the way to go). Since in an assignment a copy is created, you also need a custom assignment operator, and a destructor to free the allocated memory. More can be found on the net, for example: https://www.learncpp.com/cpp-tutorial/915-shallow-vs-deep-copying/ https://owlcation.com/stem/Copy-Constructor-shallow-copy-vs-deep-copy http://www.fredosaurus.com/notes-cpp/oop-condestructors/shallowdeepcopy.html
14th Oct 2019, 3:23 PM
Shadow
Shadow - avatar
+ 1
Ipang done
14th Oct 2019, 2:55 PM
Amit chavare
Amit chavare - avatar
+ 1
Shadow I want to do deep copy. How can i do that ? I am not getting exactly what should i do as i am having pointer of some other class im Demo class as a member
14th Oct 2019, 2:57 PM
Amit chavare
Amit chavare - avatar