Checking the constructor parameter

class item
{
    int i;

  public:
    item(int no) {

    }
};

I want to check the constructor parameter. If set to a negative value, then object creation must be stopped.

Exceptions cannot be used here because the target system does not support exceptions.

+3
source share
6 answers

It is impossible to stop the creation of an object without metalization. The best thing you can do is set the flag "invalid parameter", which you should check later, and if true, discard the object without using it.

With the requirements that you have, it would be better to use the factory method to create objects - this way you can do 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 can use this as

item* myItem = item::create(-5);
if(!myItem) {
    // failed
}

item .

+5

- , ; .

, "state", , ( , iostream).

class item
{
    int i;
    bool validState;
public:
    item(int no) : validState(true)
    {
        if(/* no is invalid */)
        {
            validState = false;
            return;
        }
        /* ... */
    }

    bool ValidState() { return validState; }

    SomeType DoSomething()
    {
        if(!ValidState())
        {
            // do nothing/report the error to the caller
        }
        // ...
    }
}

IMO , , .

+3

(, -Wall gcc).

class item
{
public:
    item(unsigned int no) {}  // item takes only +ve value
};

, -ve.

0

.

  • , .
  • item , , , , , 1.
  • factory , .

.

0

( boolean), .

class Item
{
   int i;
   bool errorState;
   public:
      Item(int n) : i(n) {
         errorState = i < 0;
      }
      bool method()
      {
        if (errorState) return false;
         ..... do stuff here

         return true;
      }
}
0

You cannot stop the construction of an object in the middle of the path without throwing an exception. Nevertheless, you can completely prevent the creation of objects of objects that do not give a precondition by moving the responsibilities of the precondition and creating objects to a separate factory function and making the constructors closed (to prohibit all other methods of constructing the object):

class item {
       int i;

   public:
       static item* create( int no )
       { 
           return no < 0 ? NULL : new item( no );
       }

   private:
       item() { ... }
       item( int no ) { ... }
};
0
source

All Articles