Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if passed arguments to constructor are correct and if not cease the creation of the object

Tags:

c++

Assume the following code:

class myClass{
    myClass(int a, int b, int c){};
};

main(){
   myClass cl(2,5,6);
}

myClass cl(2,5,6); will work. But what if I want the constructor to work only with specific values? For example a>1 b>2 c>1. Is there any way to detect wrong arguments and "cancel" the creation of cl within the constructor?


2 Answers

Yes you can do that. You just have to validate the arguments inside constructor's body. If they are invalid then throw exception.

Class Invalid
{
 private:
    int m_x, m_y;
 public :
    class MyException : public exception {};

    Invalid ( int x, int y )
    {
       if ( x < 0 || y > 100 )
            throw MyException ();
       ...             
    }
}; 
like image 174
ravi Avatar answered Dec 01 '25 21:12

ravi


You can do something like this:

myClass(int a, int b, int c)
{
    if (a <= 1){
        throw something; // ToDo - define `something`, a text string would work.
    }
}

And so on. Note one important point, the destructor will not be called if an exception is thrown in a constructor (although any base class destructors will be called). That'a quite a common cause for memory leakage.

like image 32
Bathsheba Avatar answered Dec 01 '25 19:12

Bathsheba