can constructors prevent instantiation?

I would like my constructor to validate the passed parameters. If the parameter values are not valid, I would like to refuse the instantiation of the object. Is this possible?

I tried the following, but constructors cannot return a value.

1
2
3
4
5
6
7
8
9
10
11
12
13
class TestClass()
{
  private:
    int x, y;
  public:
    TestClass(int init_x, int init_y)
    {
      if (init_x < 0 || init_y < 0)
        return DO_NOT_INSTANTIATE;
      x = init_x;
      y = init_y;
    }
};
Yes, throw an exception.
Generally speaking, constructors should not throw exceptions. A constructor has only one job: bring an object in a usable state*.
What you can do is have a Validator class that will check the parameters. If the Validator says they are ok you call the Constructor.

* there are two views on this problem: some people will tell you that a Constructor should just create an object and the initialization code should be done by another function (so the Constructor won't bring the object into a usable state, just in a "ready to be initialized state"), other people consider that the initialization is also the job of the Constructor. I think this is more of a style problem, but both groups agree that the Constructor should not throw exceptions.
Last edited on
The constructor should (and really, has no other option to but) throw an exception if it cannot create a valid object (i.e., establish the invariants of the class). Otherwise, you will have to have some kind of placeholder "bad" object that every user needs to check every time they try to use it or (worse) an object that does not work properly.
OK, thanks. I'll try the suggested techniques.
Try designing your code so it validates the input before instantiating an object?

1
2
if(argx == rightarg && argy == rightarg) CreateObject();
else std::cout << "INVALID PARAMETERS\n";
...
First of all there are things that just can’t be done right without exceptions. Consider an error detected in a constructor; how do you report the error? You throw an exception. That’s the basis of RAII (Resource Acquisition Is Initialization), which is the basis of some of the most effective modern C++ design techniques: A constructor’s job is to establish the invariants for the class (create the environment in which the member functions are to run) and that often requires the acquisition of resources, such as memory, locks, files, sockets, etc.

Imagine that we did not have exceptions, how would you deal with an error detected in a constructor? Remember that constructors are often invoked to initialize/construct objects in variables
...
- 'Why use exceptions?' https://isocpp.org/wiki/faq/exceptions
Topic archived. No new replies allowed.