Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking of constructor parameter

Tags:

c++

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.

like image 601
sukumar Avatar asked Sep 09 '11 11:09

sukumar


1 Answers

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.

like image 121
Jon Avatar answered Nov 06 '22 16:11

Jon