Hey there dear fellows,
today my teacher asked to allocate memory dynamically (an array of pointers to a class), using
new keyword
Of course that it can be done using a for loop but I thought about using a for each loop instead - that way I wouldn't need to know the array's size specifically.
Firstly, let's take a look to something I tried earlier:
int vec[3];
for each(int &v in vec)
v = 0;
I printed all vec's values and each one of them was initialized with 0
As it worked just fine, I tried to apply the same thing, but this time to allocate memory dynamically:
#include "ClassX.h"
// [...]
ClassX *vecX[3];
for each(ClassX &v in vecX)
v = new ClassX();
It doesn't work, since we got a pointer's array, but I wasn't able to figure out how to do it properly either. I tried to use reference and desreference operators attached to vecX inside for each loop, but no luck at all. It keeps raising a syntax error when I change anything
After a while, I started wondering if for each loop doesn't accept a pointer's array unless it is previously initialized(which I'm trying to do inside
)
Does anyone have a clue?
Thanks
Answer:ClassX *vecX[3];
for each(ClassX* &v in vecX)
v = new ClassX();