开发者

How can object construction of a class be stopped if a parameter passed is found to be wrong?

class Date {
    Date(int day, int month, int year) {
    }
}

int main() {
    Date d = Date(100, 2, 1990);
}

Here value(100) passed to day is not right, My question is how 'day' parameter can be ch开发者_如何学JAVAecked in constructor to prevent creation of object


Throw an exception.


#include <stdexcept>
#include <iostream>

class Date
{
public:
    Date(int day, int month, int year) {
        if (day < 1 || day > 31) { // oversimplified check!
            throw std::invalid_argument("day");
        }
    }
};

int main()
try
{
    Date d = Date(100, 2, 1990);
}
catch ( const std::exception& error )
{
    std::cerr << error.what() << std::endl;
    return EXIT_FAILURE;
}


You're creating your own "Date" function.

Just validate the arguments inside the constructor, and throw an exception if they're invalid.


Take another example

class base 
{
    public:
       base(int no, int month) 
       {
          p = new int(no);
          // some code
          // now here you have checked value of month and threw exception
       }
private:
    int *p;
};

If exception is thrown from constructor, user of the class has to be very careful to prevent memory leak. Therefore it is not a good practice. Think to solve it in other way

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜