To do what you are attempting, you would need an explicit type-cast of each array element, eg:
class T1
{
public:
int a = 1;
};
class T2
{
public:
int a = 2;
};
class T
{
public:
void **arr;
};
int main()
{
T obj;
obj.arr = new void*[2];
obj.arr[0] = new T1;
obj.arr[1] = new T2;
static_cast<T1*>(obj.arr[0])->a;
static_cast<T2*>(obj.arr[1])->a;
...
delete static_cast<T1*>(obj.arr[0]);
delete static_cast<T2*> obj.arr[1];
delete[] obj.arr;
}
However, that begs the question - how do you know which type to cast each element to? You could do something like this:
enum Ttype {typT1, typT2};
class TBase
{
Ttype type;
TBase(Ttype type) : type(type) {}
virtual ~TBase() {}
};
class T1 : public TBase
{
public:
int a = 1;
T1() : TBase(typT1) {}
};
class T2 : public TBase
{
public:
int a = 2;
T2() : TBase(typT2) {}
};
class T
{
public:
void **arr;
};
int main()
{
T obj;
obj.arr = new void*[2];
obj.arr[0] = static_cast<TBase*>(new T1);
obj.arr[1] = static_cast<TBase*>(new T2);
for(int i = 0; i < 2; ++i) {
TBase *tb = static_cast<TBase*>(obj.arr[i]);
switch (tb->type) {
case typT1:
static_cast<T1*>(tb)->a;
break;
case typT2:
static_cast<T2*>(tb)->a;
break;
}
}
...
delete static_cast<TBase*>(obj.arr[0]);
delete static_cast<TBase*>(obj.arr[1]);
delete[] obj.arr;
}
But that is ugly, and gets tedious to maintain over time as more classes are added.
You should move the common a
member into the base class, and get rid of the void*
altogether. No need for casts, let polymorphism work for you:
class TBase
{
int a;
TBase(int a) : a(a) {}
virtual ~TBase() {}
};
class T1 : public TBase
{
public:
T1() : TBase(1) {}
};
class T2 : public TBase
{
public:
T2() : TBase(2) {}
};
class T
{
public:
TBase **arr;
};
int main()
{
T obj;
obj.arr = new TBase*[2];
obj.arr[0] = new T1;
obj.arr[1] = new T2;
for(int i = 0; i < 2; ++i) {
obj.arr[i]->a;
}
...
delete obj.arr[0];
delete obj.arr[1];
delete[] obj.arr;
}