0

Let's say I have a class A :

class A{
public:
 A(int const& someValue, std::string const& anotherOne);

private:
 std::string m_string_member;
 int m_int_member;
};

And I want to allocate an array of this class using new :

A* myClassArray = new A[69];

I get the error : No default constructor available. Do I have to write a default constructor for every class I want to use by calling new ?

L. F.
  • 19,445
  • 8
  • 48
  • 82
  • 2
    What arguments do you want to construct the `A`s with? – L. F. Mar 25 '20 at 11:27
  • You just need a constructor that can be called when you construct the object. In your case, you would need a default constructor (unless you would also pass the arguments your constructor currently needs at construction). – Galan Lucian Mar 25 '20 at 11:32

2 Answers2

0

Short answer: Yes.

Long answer: Lets start with this matrix here https://foonathan.net/images/special-member-functions.png. You provide a constructor which is not the default constructor (yours takes arguments). So the compiler won't automagically generate a default constructor for you. However, in your allocation, you ask the compiler to default construct 69 elements. How should the compiler do this? But, solving this issue is rather easy. Just provide the default constructor, or, even easier, use = default. The latter only works because all your members are default-constructible.

flowit
  • 1,382
  • 1
  • 10
  • 36
0

In c++ if no user-declared constructors of any kind are provided for a class type the compiler will always declare a default constructor. If you provide any constructor and want default constructor as well, you should define default constructor explicitly.

mugiseyebrows
  • 4,138
  • 1
  • 14
  • 15