class item
{
int i;
public:
item(int no) {
}
};
I want to check the constructor parameter. If it is found to hold a negative value, then object creation should be stopped.
Exceptions can not be used here as the targeted system does not support exceptions.
There is no way to stop the creation of an object without throwing. The best you can do is set an "invalid parameter" flag that you have to check afterwards, and if true discard the object without using it.
With the requirements you have, it would probably be better to use a factory method to create the objects -- this way, you can make the checks before calling the constructor:
class item
{
int i;
public:
static item* create(int no) {
if (no < 0) {
return 0;
}
return new item(no);
}
private:
item(int no) {
}
};
You could use this like
item* myItem = item::create(-5);
if(!myItem) {
// failed
}
However, this forces you to allocate all item
instances on the heap.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With