Reputation: 149
Is it possible to assert something about the parameters on a class constructor before the initialisation list is called?
class Foo
{
int m_lower;
int m_upper;
unsigned int m_delta;
public:
Foo(int t_lower, int t_upper) :
assert(t_lower < t_upper), // Assert here, before initialisation of fields.
m_lower(t_lower),
m_upper(t_upper),
m_delta(t_upper - t_lower)
{
// Assert could be made here, but m_delta would have underflowed if t_upper < t_lower.
}
}
The benefit of an assert before the initialisation list would be that requirements for the initialisation of each field could be made immediately and would not have to be checked potentially multiple times with each initialisation that has the same requirements. Whilst initialisation of m_delta could be made in an init_delta
initialisation method, if several values have the same requirement that t_upper > t_lower
then the assertion would have to placed in each one (incase a previous assertion is removed). If placed wihtin the construct function itself, then the intialisation of one or more fields may have already failed (with something more dramatic than an underflow).
If placed at the top of the initialisation list then the contract is both clear to the user upon inspection and would flag an error before any errors, such as underflow in this case, would occur.
The above case is just a simplified example of the issue. I know there are better ways to solve the specific issue above (abs() etc).
Thanks for your help and advice!
Upvotes: 4
Views: 1609
Reputation: 781888
You can use the comma operator:
public:
Foo(int t_lower, int t_upper) :
m_lower((assert(t_lower < t_upper), t_lower)),
m_upper(t_upper),
m_delta(t_upper - t_lower)
{
...
}
Operands of the comma operator are evaluated left-to-right, and the right value is used as the result.
Note that the order of initializations is based on the order that the member variables are declared in the class, not the order in the initialization list. So you should put the assert()
call in the initialization of the first member variable.
Upvotes: 6