"Daniel Fortin" <da************@hotmail.com> wrote in message
news:d3**************************@posting.google.c om...
Hi, I was wondering if anyone knows how to overload operator new to
use a parameterized constructor.
Something like this:
class class1
{
public:
class1();
class1(int parameter1);
}
int main()
{
int number=32;
class1 * temp;
temp= new class1[number](parameter1);
}
I believe the restrictions on overloading operator 'new[]'
do not allow this. But you could write a function to achieve it:
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iterator>
template <typename T, typename PT>
T *initialized_alloc(std::size_t count, PT arg)
{
T *p = new T[count];
std::fill(p, p + count, arg);
return p;
}
class C
{
int mem;
public:
C() {} /* 'new[]' needs a default ctor */
C(int arg) : mem(arg) { } /* ctor with param */
operator int() const { return mem; } /* facilitates 'simple' */
/* output below */
};
int main()
{
std::size_t how_many(10);
C *p = initialized_alloc<C>(how_many, 42);
std::copy(p, p + how_many,
std::ostream_iterator<int>(std::cout, "\n"));
delete[] p;
return 0;
}
But this might be more trouble than it's worth. :-)
-Mike