Garbage problem in C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Garbage problem in C++

Hello, I have a need to use operators for user-defined objects. I so far wanted to make this kind of expression to work: Number n = Number(...) + Number(...); But I end up getting garbage results. (A Number object has an array attribute.) (I don't want to use pointers in the expression.) Is it even valid to run similar expressions, to strictly return user-defined objects? Otherwise the garbage might be caused by something else. Problem appears here: https://code.sololearn.com/c3Pnnnr8yp9g/#cpp

21st Sep 2020, 8:32 AM
Seb TheS
Seb TheS - avatar
3 Answers
+ 7
After some debugging, I realized that whatever object is passed to your overloaded + operator would get destroyed after the addition took place. Turns out the fix is pretty simple too, just pass RHS by reference, so that it does not get destroyed right after addition is completed. Number operator+(Number& n2) { // .... } I suggest doing the same to your overloaded comparison operator definition, so that it does not cause issues down the road.
21st Sep 2020, 9:10 AM
Hatsy Rei
Hatsy Rei - avatar
+ 7
I really thought you had a hidden sink somewhere which called delete or invoked the destructor. I was so confused lol.
21st Sep 2020, 9:13 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
Hatsy Rei Also confused, thought the garbage was caused by the n3 variable in operator+. But now it makes sense that it was caused by the n2 parameter instead. Thanks a lot!
21st Sep 2020, 9:19 AM
Seb TheS
Seb TheS - avatar