You can set the den to 1 if they try use zero, but persoanlly i would prefer to throw an exception.....maybe a bit harsh, but I dont like classes and functions that change params without notification
Also, you can use a constructor with default values...this can act as a normal default constructor, and you can add param checking in the body of the function (in this case I throw an exception)
Code:
#include <iostream>
class RationalNumber {
public:
int num,den;//these would normally be private!
RationalNumber(int n = 0, int d = 1):num(n),den(d)
{if(!den)throw DenIsSetAsZeroException();}
class DenIsSetAsZeroException{};//exception for use with class
//...extra stuff...assignments operators, copy constructors....
};
int main(){
try{
RationalNumber a;//acts like default constructor (1,0)
std::cout << "num & den = " << a.num << " " << a.den << std::endl;
}
catch(RationalNumber::DenIsSetAsZeroException&){
std::cout << "Error caught! den is zero!" << std::endl;
}
try{
RationalNumber b(10,20);//fine
std::cout << "num & den = " << b.num << " " << b.den << std::endl;
}
catch(RationalNumber::DenIsSetAsZeroException&){
std::cout << "Error caught! den is zero!" << std::endl;
}
try{
RationalNumber c(1,0);//oh dear!!!
std::cout << "num & den = " << c.num << " " << c.den << std::endl;
}
catch(RationalNumber::DenIsSetAsZeroException&){
std::cout << "Error caught! den is zero!" << std::endl;
}
}