What I’m trying to do is if the denominator is zero, I want to return an error message and delete the object. I’ve written the error message, now I need it to delete the object, or stop its creation.
Background about the program:
Rational is the name of the class. The below code is a constructor that accepts a string.
Rational::Rational(std::string inputString){
std::cout << "Inside the constructor that accepts 1 string" << std::endl;
std::stringstream ss;
ss << inputString;
ss >> numerator;
ss.ignore();
ss >> denominator;
equation = inputString;
simplifyInt();
if(denominator == 0){
std::cout << "Error. Zero on the bottom of a fraction, therefore it is undefined!" << std::endl;
std::cout << "The object was not created, because the fraction is invalid." << std::endl;
//need to add a line of code here to delete the object or stop it's creation
}
else{
std::cout << numerator << "/" << denominator << std::endl;
std::cout << equation << std::endl;
}
}
This is what I'm looking for:
User Input: Rational A("25/0");
Result: Error. Zero on the bottom of a fraction, therefore it is undefined!
The object was not created, because the fraction is invalid.
1) Throw an exception. This is really the only way to stop creation of an object.
or
2) Put the object in a known "bad" state (like set a boolean or something) and check for that bad state in all your member functions to ensure the user isn't trying to use an incomplete/bad object.
Could you go into a little more detail in what you mean by, "Throw an Exception."?
Of the two mentioned this one sounds more appealing.
The other way it sounds like I would have change my class to include one more private member that is a bool. I would then set that bool value to false in the constructor if it wasn't a valid input. Then inside my main function I would test for this false bool value when ever I did something with my object. Is that correct?