class Number
{
private: int x;
public:
Number(int _x):x(_x)
{
if (_x == 0)
//what i do here? if i don't want 0?
}
}
What is the best thing to do in this case? Exception? If it is, how i do it?
I don't want to construct the object if it is _x == 0.
thank you very much!
the point is the object still will be created and i could use it in main(). I don't want to create the object if _x == 0, or if create the object i want to delete right away so the user cant use it.
#include <stdexcept>
class Number
{
private: int x;
public:
Number(int _x):x(_x)
{
if (_x == 0)
throw std::runtime_error("attempted to create Number(0)");
}
};
Or, if you don't want x to be initialized before the check is made,
1 2 3 4 5 6 7 8 9
class Number
{
private: int x;
public:
Number(int _x) :
x(_x ? _x : throw std::runtime_error("attempted to create Number(0)"))
{
}
};