Search code examples
c++classvoid-pointers

How to access variable of an object from within an other object stored in void pointer


I have to make a dynamic array in a class and store another class' object in that array. Then use the array to access the other classes. there are a total of 3 classes to be stored in that same array.

But when I try to access the var, it wont allow me to... (obj.arr[0].a;) This one. I tried many ways but cant find any solution. please help.

Code:

class T1
{
public:
    int a = 1;
};

class T2
{
public:
    int a = 2;
};


class T
{
public:
    void *arr[];
};

int main()
{

    T obj;

    obj.arr[0] = new T1;
    obj.arr[1] = new T2;

    obj.arr[0].a;
}

Solution

  • It does not want to let you, because a void* has no member named a. You have to let the compiler know that you want to pretend the void* is actually a T1*.

    That being said, this is a terrible practice. One of the advantages of c++ over c is that it provides a way of avoiding the need to force-polymorphism like this. A much better way would be to make all classes inherit a common base class (and instead of void pointers, use pointers to that base class in your array). If virtual methods satisfy your needs, use those, otherwise use dynamic_cast (https://en.cppreference.com/w/cpp/language/dynamic_cast) to retrieve the whole objects.

    If you still insist on retrieving the object from the void*, do so using static_cast, and triple-check that you have actually put the object under that pointer.

    static_cast<T1*>(&obj.arr[0])->a;
    

    Your void*[]'s size is also not initialized, but I assume that is only for simplicity?