Before I begin, I want to clarify that this is actually a pretty big topic in C++, and many design patterns are explicitly designed around this problem.
A nieve approach is to throw an exception in the contructor:
class myClass {
public:
myClass(int a, int b, int c)
{
if (a<=1 || b <= 2 || c<=1) throw "some exception";
}
};
This is generally considered a bad practice, as the destructor for the class will never be called! As a rule of thumb, constructors should be fast and simple. If a constructor can fail, you should try something else. Also, exception handling is notoriously slow in C++.
So alot of people go with the an initialize call instead:
class myClass {
public:
myClass() { initialized_ = true;}
void initialize((int a, int b, int c) { initialized_ = !(a<=1 || b <= 2 || c<=1);}
bool alive() {return intialized_;}
private:
bool initialized_;
};
Then, when you use the class you can check after an initialization attempt if the object succeeds.
myClass c;
c.initialize(2,5,6);
I personally don't like this because you end up with zombie classes.
myClass c;
c.initialize(0,0,0);
c.foo();//Legal, compiles, but is WRONG
This Zombie Class apposes the idea of RAII, and honestly I shouldn't have to do that check all the time.
My prefered way of dealing with this is factory methods.
class myClass
{
public:
static myClass* makeMyClass(int a, int b, int c)
{
myClass* ret = new myClass();
ret->initialize(a,b,c);
if (!ret->alive()) {delete ret; return null;}
return ret;
}
private:
myClass() { initialized_ = true;}
void initialize((int a, int b, int c) { initialized_ = !(a<=1 || b <= 2 || c<=1);}
bool alive() {return intialized_;}
private:
bool initialized_;
};
(protip don't use raw pointers, use smart pointers).