Reputation: 101
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
Upvotes: 10
Views: 36085
Reputation: 9602
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;
}
Upvotes: 9
Reputation: 62583
In c++03 you initialize vector through it's constructor, which is pretty awkward, since you will have to copy it frome some place else. For example:
static int initializer[] = {1, 2, 3};
ClassA::ClassA() : m_Vec(initializer, initializer + sizeof(initialize) / sizeof(int)) {}
In C++11, this all goes away. In constructor:
ClassA::ClassA() : m_Vec{1, 2, 3, 4} {}
In-place:
std::vector<int> m_Vec{1, 2, 3, 4};
Upvotes: 8
Reputation: 117876
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;
};
Upvotes: 15
Reputation: 3365
Like this:
class ClassA {
const std::vector<int> m_Vec {1,2,3};
};
Or this:
class ClassA {
ClassA () : m_Vec {1,2,3} {}
const std::vector<int> m_Vec;
};
Upvotes: 3