GordoN
GordoN

Reputation: 35

Using new to allocate an array of class elements with an overloaded constructor in C++

As an example say I have a class foo that does not have a default constructor but one that looks like this

foo:foo(int _varA,int _varB)
{
   m_VarA = _varA;
   m_VarB = _varB;
}

How would I allocate an array of these.

I seem to remember trying somthing like this unsuccessfully.

foo* MyArray = new foo[100](25,14).

I don't think this will work either.

foo* MyArray = new foo[100](25,14)

Can this be done? I typically do this by writing the default constructor using some preset values for _varA and _varB. Then adding a function to reset _varA and _varB for each element but that will not work for this case.

Thanks for the help.

Upvotes: 0

Views: 409

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754450

If you are to be able to allocate an array of a class (directly, using new[]), the class must have a default constructor. No default constructor, no dynamic arrays.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490338

Your first choice should be to ignore the fact that new[] even exists, and use an std::vector instead:

std::vector<foo> MyArray(100, foo(25,14));

Upvotes: 5

Related Questions