1
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 checked in constructor to prevent creation of object

yoozer8
  • 7,361
  • 7
  • 58
  • 93
sukumar
  • 131
  • 1
  • 7

4 Answers4

10

Throw an exception.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
7
#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;
}
André Caron
  • 44,541
  • 12
  • 67
  • 125
0

You're creating your own "Date" function.

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

paulsm4
  • 114,292
  • 17
  • 138
  • 190
-3

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

Alok Save
  • 202,538
  • 53
  • 430
  • 533
sukumar
  • 377
  • 1
  • 6
  • 4
    No, One should use **RAII** so that the resources are deallocated automatically and no explicit deallocations are needed. – Alok Save Aug 04 '11 at 04:02
  • 1
    Actually, throwing an exception from a constructor - if the object cannot be created (for example, because of invalid arguments) is generally an EXTREMELY good idea. James' original reply is the correct reply. Please consider that if you follow good RAII design principles, this need NOT risk causing any kind of resource link or inconsistency. Please look at these links: http://stackoverflow.com/questions/161177/does-c-support-finally-blocks-and-whats-this-raii-i-keep-hearing-about http://en.wikibooks.org/wiki/C++_Programming/Exception_Handling#Constructors_and_destructors – paulsm4 Aug 04 '11 at 04:05
  • 1
    PS, Sukumar: Please mark James' or Andre's answer "accepted" after you've read the two links and satisfied yourself they're giving you good advice :) – paulsm4 Aug 04 '11 at 04:09
  • 6
    Throwing an exception is standard practice: http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8 Being careful to prevent memory leaks is **not** a job for the user of the class; it's a job - an absolutely mandatory one - for the designer of the class. Fortunately, it is not all that hard to get right, if you use proper tools and idioms. – Karl Knechtel Aug 04 '11 at 04:11