Error when writing Parameterized constructor for class with vector of objects

I am getting the error "" when trying to writing parameterized constructor for the B class. B class holds a vector of A class objects. Kindly help me with this issue.

#include <iostream>
#include <vector>

#define NUMBER 10
class A
{
    int x;

public:
    A(int a) : x(a) {}
};

class B
{
    std::vector<A> vec[NUMBER];
public:
    B();
};

B::B() : vec(NUMBER, A(10)) {}

int main()
{
    B b;
    return 0;
}

Error occurring while compiling:

check.cxx: In constructor ‘B::B()’:
check.cxx:20:10: error: expression list treated as compound expression in mem-initializer [-fpermissive]
   20 | B::B() : vec(NUMBER, A(10)) {}
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
check.cxx:20:10: error: invalid initializer for array member ‘std::vector<A> B::vec [10]’

Also, help me with writing default and copy constructors ??

>Solution :

The problem is that std::vector<A> vec[NUMBER]; defines an array of size NUMBER with elements of type vector<A>.

To solve this either replace std::vector<A> vec[NUMBER]; with just std::vector<A>; or with std::vector<A> vec = std::vector<A>(NUMBER); as shown below:

Method 1

Here we replace std::vector<A> vec[NUMBER]; with:

class B
{
    std::vector<A> vec; // no need to use NUMBER here
public:
    B();
};

Note the default constructor initialized the vector member so there is no need to do it in the in-class initializer(as shown above).


Method 2

Here we use in-class initialzer.

class B
{
    std::vector<A> vec = std::vector<A>(NUMBER);  //corrected syntax
public:
    B();
};

working demo

Leave a Reply