I have a const vector as member in a class. How can I initialize it?
I know that for constant members the only way we can initialize them is via list initialization at class's constructor function. But exactly how to do it with a vector, I do not know.
For example,
class ClassA
{
const std::vector<int> m_Vec;
};
Thanks
You can initialize the vector in the class declaration
class ClassA
{
const std::vector<int> m_Vec = {1,2,3};
};
Or in the constructor using member initialization
class ClassA
{
public:
ClassA(std::vector<int> const& vec) : m_Vec(vec) {}
private:
const std::vector<int> m_Vec;
};
I have a const vector as member in a class.
First, I would generally say that you want to avoid it prevents using the class in expected ways (see example below). Also, if the data member is completely encapsulated in the class there is no reason it cannot be a non-const data member while using the classes interface to guarantee it's treated in a const way (i.e., instantiations of the class have no way to modify the data member).
class ClassA
{
const std::vector<int> m_Vec;
};
int main()
{
ClassA c1;
ClassA c2;
// ...
c1 = c2; // This doesn't compile!
return 0;
}
How can I initialize it?
The other answers provide a few different ways to initialize the const data member but here is one that I didn't see in the other answers: use a function. I think an advantage to using a function could be if the initialization is complex and possibly dependent on runtime input (e.g., you could update the init
function to take external state to modify how the std::vector
is initialized).
#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;
}
#include <vector>
class ClassA
{
public:
ClassA() : m_Vec(init()) {}
private:
static 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With