I have abstract class A
class A{
public:
A(dim) : dim_(dim);
private:
int dim_;
}
and class B
class B : public A{
public:
B(int dim);
}
and I need to make constructor for class B, which works only when dim > 1 and throw assertions otherwise.
in this case
B::B(int dim) : A(dim){
assert(dim > 1);
}
it works, but it’s not good solution I think, because instance of the class A was created and deleted.
Than I make init-method for class A:
class A{
public:
void init(int dim){
dim_ = dim;
}
A(int dim){
init(dim);
}
private:
int dim_;
}
and change constructor of class B:
class B : public A {
public:
B(int dim){
assert(dim > 1);
init(dim);
}
}
but it doesn’t work. Is there any possible solutions for my problem?
I think you could write a small
myintclass which makes sure that theintyou pass is always greater than1:Now use it in your class:
Note that you can still construct
Bpassingint, as it will implicitly convert intomyintand while the conversion takes place (implicitly), it will test the assert, and if that succeeds, only then you would be able to passdim.datato the base classA. If the assert fails, your program will abort before entering into the base class constructor (without initializing anything in derived class also).You could even generalize it as:
Now use it in your class:
If you need another class, for example:
Cool, isn’t?