Search code examples
c++arraysconstructorinitializationinitialization-list

Arrays in the initialization list of a constructor


I'm trying to figure out how to declare an array of an arbitrary size in the constructor's initialization list. If this isn't possible, what should I do instead?

For example:

class vectorOfInt
{
public:

private:
    int _size;
    int _vector[];
};

vectorOfInt::vectorOfInt()
    :_size(32),
    _vector(size)
{
}

Basically, I want the array _vector to be initialized to size (32 in this case). How do I do that? Thanks for any input.


Solution

  • Use an std::vector:

    #include <vector>
    
    class vectorOfInt
    {
    public:
    
    private:
        int _size; // probably you want to remove this, use _vector.size() instead.
        std::vector<int> _vector;
    };
    
    vectorOfInt::vectorOfInt()
        :_size(32),
        _vector(size)
    {
    }
    

    Edit: Since you don't want to use std::vector, you'll have to handle memory yourself. You could use a built-in array if you knew the size of the array at compile time, but I doubt this is the case. You'd have to do something like:

    #include <memory>
    
    class vectorOfInt
    {
    public:
    
    private:
        int _size;
        // If C++11 is not an option, use a raw pointer.
        std::unique_ptr<int[]> _vector;
    };
    
    vectorOfInt::vectorOfInt()
        :_size(32),
        _vector(new int[size])
    {
    }