Usually when you have a constant private member variable in your class, which only has a getter but no setter, it would look something like this:
// Example.h
cl
You have two basic options. One is to use the conditional operator, which is fine for simple conditions like yours:
Example::Example(const std::vector &myVec)
: m_value( myVec.size() ? myVec.size() + 1 : -1)
{}
For more complex things, you can delegate the computation to a member function. Be careful not to call virtual member functions inside it, as it will be called during construction. It's safest to make it static
:
class Example
{
Example(const std::vector &myVec)
: m_value(initialValue(myVec))
{}
static int initialValue(const std::vector &myVec)
{
if (myVec.size()) {
return myVec.size() + 1;
} else {
return -1;
}
}
};
The latter works with out-of-class definitions as well, of course. I've placed them in-class to conserve space & typing.