Search code examples
c++c++11stdarray

What is the syntax for std::array as a field, and objects inside must be constructed with ctor that takes parameters?


class Bar
{
Bar( var1 v1, var2 v2 )
    {
    // setup Bar fields
    }
// bar fields
}    

class Foo
{
Foo()
    :
    mArray();// how to do this part
    {

    }
std::array<Bar, 800> mArray;
}

I need to construct this array with some values using the ctor that bar provides that takes in some parameters, it's ok if they are all constructed to the same values because later I will assign them proper values I just have to get it initialized. I've googled this and tried many different syntax but for some reason I can't get it right.


Solution

  • The problem is that Bar doesn't have a default constructor, so std::array<Bar> doesn't have one either.

    If you add a default constructor to Bar, std::array<Bar> will have one too:

    #include <array>
    using namespace std;
    
    typedef int var1, var2;
    
    class Bar
    {
    public:
    Bar() {} // <--------- HERE
    
    Bar( var1 v1, var2 v2 )
        {
        // setup Bar fields
        }
    // bar fields
    };    
    
    class Foo
    {
    Foo()
        :
        mArray()
        {
    
        }
    std::array<Bar, 3> mArray;
    };