-1
class Date
{
private:
    int Day;
    int Month;
    int Year;
    bool CheckDate(int InputDay, int InputMonth, int InputYear);
    // this return true when the date is valid

public:
    Date(int InputDay, int InputMonth, int InputYear);
    ~Date();
};



Date::Date(int InputDay, int InputMonth, int InputYear)
{
    if (!CheckDate(InputDay, InputMonth, InputYear))
    {
        cout << "Date Invalid!\n";
        this->~Date(); 
        // this invokes the destructor
        // however at the end of the program the destructor would invoke again
    }
    else
    {
        Day = InputDay;
        Month = InputMonth;
        Year = InputYear;
    }
}

I find a resource here How can object construction of a class be stopped if a parameter passed is found to be wrong?. Is there a way to do it without exception? Is there a way which the constructor check the parameter itself and destruct itself?

Community
  • 1
  • 1
tom
  • 1,302
  • 1
  • 16
  • 30

4 Answers4

0

I'd suggest this

Date::Date(int InputDay, int InputMonth, int InputYear) {
    if (!CheckDate(InputDay, InputMonth, InputYear))
        throw "Date Invalid!\n";    // throw exception
    else {
        Day = InputDay;
        Month = InputMonth;
        Year = InputYear;
    }
}

Also, use try-catch block to catch the exception and declare CheckDate as static.

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
0

As said by Jerry Coffin, there is no proper way to stop construction of an object except by throwing an exception.

The only alternative would be to have a boolean (valid) in your class, and caller should test it after creation and delete (or reset or whatever) if it was false. But it would rely on caller doing the right thing instead of processing the error condition in the class itself.

The exception have this special value : caller can catch them if he wants, but if it just do not care, the exception ensures that a badly constructed object cannot be used inadvertantly.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

you can't call this->~Date() in function Check Date. In calss Date function, one class can't deconstruct itself in it's function, it's only use out class. if the check fail, you can throw exception, don't deconstruct class.

Liyuan Liu
  • 172
  • 2
0

As Matt says raise an exception.

In the alternate, you could use a pointer.

Consider how the date class looks like to a user.

...
Date due(a,b,c);
...

There is no way to tell if due is invalid if you back out halfway. The only way is to throw an exception.

The alternate way ( using a unique_ptr wrapper ) is to make a function:

unique_ptr<Date> due=makeDate(d,m,y)

unique_ptr<Date> makeDate(int d,int m,int y)
{
  if( CheckDate(d,m,y)) // make your Checkdate function static.
     return make_unique<Date>(d,m,y);
  else
     return make_unique<Date>(nullptr);
}

Double check everything there, My unique_ptr semantics aren't yet up to snuff :)

TLOlczyk
  • 443
  • 3
  • 11