views:

47

answers:

2

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.

+5  A: 

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));
Jerry Coffin
Great advice. Why worry about all the details to get placement new right when you can use a known working and tested implementation?
Ben Voigt
A: 

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.

Jonathan Leffler