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
Use a static member function the compute to result you need and call that function in the initialization list. Like this:
// Example.h
class Example {
public:
Example(const int value);
Example(std::vector myVec);
const int getValue() const;
private:
const int m_value;
static int compute_m_value(::std::vector &myVec);
};
// Example.cpp
#include "Example.h"
Example::Example(const int value)
: m_value(value)
{
}
Example::Example(std::vector myVec)
: m_value(compute_m_value(myVec))
{
}
const int Example::getValue() const
{
return m_value;
}
int Example::compute_m_value(::std::vector &myVec)
{
if (myVec.size()) {
return myVec.size() + 1;
}
else {
return -1;
}
}
In this particular case, the function is so very simple you can simply use the ternary operator (aka : m_value(myVec.size() > 0 ? int(myVec.size() + 1) : int(-1)
) in the constructor to directly compute the value at initialization. This looked like an example, so I gave you a very general method of solving the problem, even when the method of computing the answer you need might be very complex.
The general issue is that constant member variables (and member variables that are references too BTW) must be initialized in the initializer list. But initializers can be expressions, which means they can call functions. Since this initialization code is pretty specific to the class, it should be a function private (or maybe protected) to the class. But, since it's called to create a value before the class is constructed it can't depend on a class instance to exist, hence no this
pointer. That means it needs to be a static member function.
Now, the type of myVec.size()
is std::vector
, and that type is unsigned. And you're using a sentinel value of -1, which isn't. And you're storing it in an int
which may not be the right size to hold it anyway. If your vector is small, this likely isn't an issue. But if your vector acquires a size based on external input, or if you don't know how large it will get, or any number of other factors, this will become an issue. You should be thinking about that and adjusting your code accordingly.