Overloaded assignment operator | Return type and memory reallocate | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Overloaded assignment operator | Return type and memory reallocate

HI Below is what I did for overloaded assignment operator: https://code.sololearn.com/c7Q51Kdekh7p I overloaded assignment and it's return type is void. Still I am able to compile and get desired output. How it is possible? When we need to have return type as ref to object instead of void as of now? Another concern is about obj2=obj3; This means I am copying "busy" to "is". When we created obj2 , through constructor; I reserved 3 bytes due to len +1 where as busy needs 4+1 bytes. Howcome code is still working?

22nd Jun 2020, 10:37 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 1
Ketan Lalcheta Assignment operator is such that it requires at least one argument. If overloaded assignment operator is returning void in case of a = b = c; a, b, c are all variable of myString type objects. here b = c; returns void when a = b is compiled it can be written as a.operator = (b = c); It fails because b = c returns void and it will fail because it must have argument. When we overload operator "basic operator property" (like number of arguments) doesn't change. operator = has atleast one argument and because of void argument it fails to compile
23rd Jun 2020, 8:52 PM
DHANANJAY PATEL
DHANANJAY PATEL - avatar
+ 1
Ketan Lalcheta Returning void instead of reference in overloaded assignment operator limits following chaining of assignment operator. a = b; // void return type a = b = c; // ref as return type In case of assignment operator if there is memory allocated it needs to reallocated and before that previously allocated memory needs to be freed. Then content needs to be copied. Whatever is done in above code is risky it can crash the application program, it needs to be corrected. It crashes because of illegal access or corruption of heap (manages memory allocation).
23rd Jun 2020, 1:31 PM
DHANANJAY PATEL
DHANANJAY PATEL - avatar
0
DHANANJAY PATEL , thanks a lot... I updated the code... However, I could not get why a= b=c is not working for void return type...?
23rd Jun 2020, 7:20 PM
Ketan Lalcheta
Ketan Lalcheta - avatar