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

4
  • can you simply use std::vector<>? Commented Oct 12, 2018 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 Commented Oct 12, 2018 at 18:14
  • Check the update, I can't use the vector library Commented Oct 12, 2018 at 18:17
  • 3
    @MarkDodds All of the headers you name are in the same library as <vector>. That's the standard library. It wouldn't be surprising for one of the ones you named (like string) to be using <vector>. Commented Oct 12, 2018 at 18:24

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

"you no longer have a default constructor defined for you" - can be fixed by writing one, or if the default one is sufficient, declare it as = default;.
@JesperJuhl Which the OP cannot do
@JesperJuhl good point. Added that creating your own default c'tor is definitely an option.
Pity you can't just take advantage of aggregation.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.