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?
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 ();
...
}
};
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.
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