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
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.
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.
Here is an example of shallow copying:
Versus a deep copy:
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: