Dynamic memory allocation

i have a class as below
1
2
3
4
5
6
7
8
9
10
class Test
{
	int m_nNum;
public:
	Test( int nNum_i )
	{
		m_nNum = nNum_i;
	}
	
};


is there anyway to create a dynamic array of 10 Test Objects. remember Test has no default constructor. I need to get something like

1
2
Test* TObj = 0;
TObj = new Test[200];


it would be enough if i could at least static array.pls help
For a static array, you can do this:
Test array[200]={3,1,4,1,5...};
Athar, it will not work.
Couldn't you just make a constructor with no parameters, and fill in the variables after declaration? Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Test
{
	int m_nNum;
public:
	Test( int nNum_i )
	{
		m_nNum = nNum_i;
	}
	Test()
	{
	// initialize variables that
	// don't require arguments
	}
	setvars( int nNum_i )
	{
	m_nNum=nNum_i;
	}
};
No, there's no way to pass constructor parameters to objects constructed as part of dynamically allocated arrays.
Reannah wrote:
Athar, it will not work.

It will.
if you change your Test constructor to this.

Test(int nNum_i=0)
{
m_nNum = nNum_i;
}

it is default constructor with default argument,it will solve 2 purposes,it can use to construct object using dynamically allocated memory or simple object with arguments or withour arguments also.

hope this will solve ur problem.
You could reserve the memory and later construct the elements (one by one).
1
2
3
4
5
6
7
//allocator<Test> aux;
//Test *const array = aux.allocate(n);//reserve a block of memory 
Test *const array =(Test *) malloc( sizeof(Test)*n );

//construct 1 object
//new ((void*)(array+i)) Test(value);
new (array+i) Test(value);


Or use Test **, or an STL container
Last edited on
Topic archived. No new replies allowed.