sam
BAN USERfirewithin and kk's solutions are right but do not scale to a large number such as 500. A better way is to allocate just one large raw chunk of memory and use placement new to initialize all the objects. The following program initializes 500 objects using integer values 1 to 500.
struct A { A(int i) {} };
int main(void) {
const int N = 500;
A * ptr = static_cast<A *>(::operator new (sizeof(A) * N));
for(int i = 0;i < N; ++i)
{
new (ptr + i) A(i); // placement new
}
// Don't forget to call destructors at the end.
for(int i = 0;i < N; ++i)
{
(ptr + i)->~A();
}
// free memory.
::operator delete (ptr);
}
A few differences:
1. If class that has an overloaded new operator, can not use base class's values to initialize its own values in its new operator. This is possible only in the constructor.
2. If new is overloaded for class B and D inherits from B, then "new D()" will call B's new operator. This behavior is different from how constructors behave.
3. If new [] is overloaded for class B then "new B[N]" gets only one chance to initialize N objects. You will need a loop. With constructors, however, one constructor will be called for each object. No loop needed.
- sam March 20, 2016