Tip for Fraction class

Hey guys, I'm making my own Fraction class.

I have a method that simplifies the fraction by diving numerator and denominator for their G.C.D

1
2
3
4
5
6
7
Fraction Fraction::Simplify()
{
	int GCD = getGCD(numerator, denominator);
	numerator /= MCD;
	denominator /= MCD;
        return *this;
}


Here i have a doubt. Should I return a copy of the Fraction?

I actually modify the fraction which calls the function, but I want to be also able to do something like this:

1
2
3
4
Fraction newFrac = oldFrac.Simplify();

// or even
cout << newFrac.Simplify();


In this cases, is the return-by-copy worth it? Or should I return by reference?
Last edited on
is the return-by-copy worth it?


In what sense? As far as I can tell, the only benefit of what you're doing is a tiny bit less typing, so you don't have to do this:

1
2
oldFrac.Simplify();
Fraction newFrac = oldFrac;
Last edited on
Should I return *this by reference or by copy?
Last edited on
Since you're modifying the object, return a reference. There is no reason to both modify the original object and force the creation of a new object.
Topic archived. No new replies allowed.