I have a constant vector as a member in a class.
First, I would say that you want to avoid this in order to prevent the class from being used in the expected ways (see example below). In addition, if a data element is fully encapsulated in a class, there is no reason why it cannot be a non-constant data element when using the class interface to ensure that it is processed in const (i.e. class instances do not have the ability to modify the data element) .
Bad example
class ClassA { const std::vector<int> m_Vec; }; int main() { ClassA c1; ClassA c2;
How can I initialize it?
Other answers provide several different ways to initialize a const data element, but there is one that I have not seen in other answers : use a function . I think that the advantage of using a function can be if the initialization is complicated and possibly depends on the input at runtime (for example, you can update the init
function to take an external state to change the way std::vector
initialized).
Free function example
#include <vector> namespace { std::vector<int> init() { std::vector<int> result; // ... do initialization stuff ... return result; } } class ClassA { public: ClassA() : m_Vec(init()) {} private: const std::vector<int> m_Vec; }; int main() { ClassA c1; return 0; }
Member Function Example
#include <vector> class ClassA { public: ClassA() : m_Vec(init()) {} private: std::vector<int> init() { std::vector<int> result; // ... do initialization stuff ... return result; } const std::vector<int> m_Vec; }; int main() { ClassA c1; return 0; }
source share