I have an assignment that my teacher has told us to use this in the .h file:
operator string();
and we can not deviate from it in any way.
So in my .cpp file I have:
Currency::operator string(){
stringstream output;
output<<"$";
output<<dollars;//Why does this return garbage for money1+money2??
output<<".";
output<<cents;
string outputstring = output.str();
return outputstring;
}
But when I do string(money1+money2) it returns garbage, it works fine when I just do ‘string(money1)`. I am wondering what I am doing wrong.
Any help will be great.
Here is my overloaded + operator code:
Currency& Currency::operator+(const Currency &rhs){
Currency temp;
temp.dollars = dollars + rhs.dollars;
temp.cents = cents + rhs.cents;
temp.simplify();
return temp;
}
Notes: I have run the debugger and there is no issue with the overloaded + operator; it returns what it should.
You are returning a local variable by reference. Never do this.
You should be returning it by value: