Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading