How to instantiate static array of interlaced objects?

The following code instantiates a static array of interlaced objects.
The objects alternate between type AClass and type Bclass.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

class Base { };
class AClass: public Base { };
class BClass: public Base { };

int main()
{
	const int num=4;
	Base * array[num];

	AClass obj0;
	array[0] = &obj0;
	AClass obj1;
	array[1] = &obj1;
	AClass obj2;
	array[2] = &obj2;
	AClass obj3;
	array[3] = &obj3;

	for (int i=0; i<num; i++)
	{
		cout << "addr = " << array[i] << endl;
	}

	return 0;
}


I want to the code to instantiate the array in a way that if num changes, the user only needs to change num in the config.h file and recompiled.

Here is one idea that did not work:
1
2
3
4
5
6
7
	for (int i=0; i<num; )
	{
		AClass objA;
		array[i++] = &objA;	// same addr on each iteration
		AClass objB;
		array[i++] = &objB;	// same addr on each iteration
	}


Thanks for taking a look.
You need to use dynamic memory for the objects (but not necessarily for the array).
Thanks LB. This worked:
1
2
3
4
5
	for (int i=0; i<num; )
	{
		array[i++] = new AClass;
		array[i++] = new BClass;
	}
Don't forget to delete them afterwords!
Topic archived. No new replies allowed.