Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a member const vector of a class C++

Tags:

c++

vector

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

like image 930
rudky martin Avatar asked Feb 25 '16 18:02

rudky martin


2 Answers

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;
};
like image 60
Cory Kramer Avatar answered Oct 19 '22 03:10

Cory Kramer


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).

Bad Example

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).

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:
    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;
}
like image 42
James Adkison Avatar answered Oct 19 '22 04:10

James Adkison