### Design Review

I started to learn C++ recently and as a starter was asked to design a class for fractions which can do *,+,- and / . This is the class that I designed. Are there any flaws in the design? Can anybody please help me?

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153`` `````` #include #include using namespace std; class Fraction { int numerator; int denominator; public: Fraction() // Default constructor { numerator = 0; denominator = 1; } Fraction(int n,int d) // parameterized constructor { numerator = n; if(d==0) { cout<<"Divide by zero error : Fraction Created as 0/1 \n"; numerator = 0; denominator = 1; } else denominator = d; //Alternatively this can be used depending on if we want the program to be terminated in case of bad input /*try { if(d==0) throw std::overflow_error("Divide by zero exception"); else { numerator = n; denominator = n; } } catch(std::overflow_error& e) { cout< (a.numerator * lcm_value/a.denominator)) return true; else return false; } void print_fraction() // Function for printing the fraction { cout<
You're showing an implementation, not a design document. Working back to what the design might have been , I would ask why is the public interface so unusual for a value-semantic type: it is neither equality-comparable nor less-then-comparable, and therefore can't be used with standard C++ containers and algorithms. I would also recommend removing the copy ctor and dropping surprise output statements from ctor and dtor (at which time dtor can be removed too). Of course you're not showing the specs, so it's possible that this output is a requirement, but if it's just to implement the mathematical fraction type, take a look at std::complex for design ideas.
I think code wise its pretty well designed. To full advantage of the language though I would use operator+, operator-, operator*, operator/, operator<, operator>, operator==, and operator>> instead of the alternate Java function names add, subtract...etc.
Look up operator overloading. I think you'll like the feature but remember to employ those features in moderation. In this case I would think it would be appropriate though.
Topic archived. No new replies allowed.