c++ - Pointer to class -


i have been trying write fraction class , overload of operators (+, -, -, /...). @ first, tried this:

fraction& operator+(fraction& rightop) {     fraction result;     result.num = num * rightop.den + den * rightop.num;     result.den = den * rightop.den;;     return result; } 

this produced awkward result. while testing, if used:

fraction a(2,3); fraction b(4,5); fraction c = + b; cout << c << endl; 

it print correctly. however, if used:

fraction a(2,3); fraction b(4,5); fraction c; c = + b; cout << c << endl; 

it print -858993460/-858993460.

then, when tried change overloading function to:

fraction& operator+(fraction& rightop) {     fraction* result = new fraction;     result->num = num * rightop.den + den * rightop.num;     result->den = den * rightop.den;     return *result; } 

it work well. got me confused pointing classes in c++, not understand why first 1 fails in specific case. appreciate explanation.

thanks in advance.

note: operator << not source of problem here anyway:

friend ostream& operator<<(ostream& out, fraction& f) {     out << f.num << "/" << f.den << endl;     return out; } 

fraction& operator+(fraction& rightop) {     fraction result;     result.num = num * rightop.den + den * rightop.num;     result.den = den * rightop.den;;     return result; } 

the problem it's returning reference local variable. local variable destroyed when function ends, reference refers invalid object.

using new instead has solved problem because makes result object dynamically allocated. such object not destroyed @ end of function. however, not solution here. unclear user of operator+ reference returned refers dynamically allocated object , needs deleted in future. never put burden on users.

instead, should change function returns value:

fraction operator+(fraction& rightop) {   // ...   return result; } 

this return copy of result, doesn't matter if result destroyed @ end of function.

as additional note, want function take const fraction& argument. allows called when second operand rvalue (typically temporary object).


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -