-2

I have the following class and struct (stripped down for simplicity)

a.h

class A {
    B *myArray;
}

a.cc

A::A() {
    myArray = new B[1];
}

b.h

struct B {
    int number;
}

b.cc

B::B(int n): number(n)  {
}

As you can see the class B only has the constructor that takes an integer, so when I do myArray = new B[1] it throws no matching constructor for initialization of 'B[1]'.

How can I fix this? I've tried doing an array of pointers instead of an array of type B but it doesn't work because of the way information is entered into the program.

I cannot add a new constructor to B. I can only add private variables and methods. I can only use the following libraries: iostream, fstream, sstream, iomanip, string, and utility.

BigSpicyPotato
  • 739
  • 5
  • 18
  • can you simply use `std::vector<>`? –  Oct 12 '18 at 18:13
  • 1
    Use a `std::vector` instead. It has functionality built in to handle non-default constructable types. For every dynamic array, there is a vector that will solve it's problems – NathanOliver Oct 12 '18 at 18:14
  • Check the update, I can't use the vector library – BigSpicyPotato Oct 12 '18 at 18:17
  • 3
    @MarkDodds All of the headers you name are in the same library as ``. That's the standard library. It wouldn't be surprising for one of the ones you named (like `string`) to be using ``. – François Andrieux Oct 12 '18 at 18:24

2 Answers2

2

Since you define a constructor for B, you no longer have a default constructor defined for you.

When you do myArray = new B[1]; you're trying to build an array of size 1 while calling B's default constructor, but no such constructor exists!

This can be fixed by either making your own default B constructor, or calling the constructor you made when allocating. The latter can be done with:

myArray = new B[1]{5};

See it work here: ideone

scohe001
  • 15,110
  • 2
  • 31
  • 51
1

The issue is that you don't have a default constructor to B. You have to provide one or at least a default value for the only parameter (also the constructor should be tagged as explicit.

Another option is to use a vector. You should avoid any explicit delete anyway, so it's a better option to what you have.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62