operator new and parameterized constructor

D

Daniel Fortin

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);
}

Thanks
 
M

Mike Wahler

Daniel Fortin said:
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::eek:stream_iterator<int>(std::cout, "\n"));

delete[] p;
return 0;
}

But this might be more trouble than it's worth. :)

-Mike
 
R

Rolf Magnus

Mike said:
Daniel Fortin said:
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:

Or just use std::vector:

std::vector<class1>(number, class1(parameter1));

However, that does not initialize each element with parameter1, but
rather copy-construct them from the temporary you give as argument.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,825
Members
47,371
Latest member
Brkaa

Latest Threads

Top