C++ Fractions Class

C++ Fractions Class

You may want to start with just the first part, create the class with two constructors, one if they give the two numbers, and one that defaults to 1.

Then, write the four functions, the assignment is nice enough to give you the equations.

If a denominator is ever equal to zero then I would throw an exception, as that is something the user may be able to fix. If you can show what led to it being zero, for example, if they divide (1/2)/(0/4) then your denominator is zero, which should be an error condition.

One issue you will want to look at is if this will be immutable, so, if I have (1/2) and (2/3) and I do an operation, it should return a new number, not modify either of the two that I passed in. In that case your check is always in the constructor for a zero, but you should explain which operation led to this error.

Also what would be a good way to prohibit denominator of 0? Throw exception or force it to be equal to 1?

Thats completely a style question, with no provably correct answer…

But… Id go with an exception. Again, this is just style. Changing the value silently would be carrying on silently forward having done something other than what the caller asked for.

Another alternative would be to allow 0 denominator, but have a way to inform the user that the current overall value, a/b, is NaN or infinity, or whatever special value you care to define.

In any case, document it carefully, so a user of the class can make informed choices.

C++ Fractions Class

Your fraction constructor should take a numerator and a denominator as parameters (or a whole number). The entire problem could be solved easily with operator overloading.

And yes, the best way to handle failed constructors is via exceptions. Dont forget to throw the same division_by_zero exception when youre dividing two fractions and the numerator of the denominator is zero.

Leave a Reply

Your email address will not be published.