2

I have a void pointer in C++, void *p=NULL; Now, some processing makes this pointer point to an object of some class. There are 3 classes in my case and the pointer can be pointing to an object of anyone of these classes. Is there a way that I check which class's object is it pointing at.

Also can I access the object's class's methods through the void pointer or do we have to cast the void pointer?

  • You can have a generic class above all three which holds a non-private variable `type`, probably an integer. Set types of child classes at construction time. – no more sigsegv Jun 02 '22 at 05:39
  • Once you erase all of a type's information by casting it to `void` you're hosed. Best you can do is guess. If there is sufficient commonality between the three classes, a base class for example, you can call a common function that identifies the type and then cast to the correct type. You could also keep a map of pointers and type information and use that to identify based on the address of the object. – user4581301 Jun 02 '22 at 05:39
  • the compiler will be unhappy if you try to invoke methods on a `void` pointer. `void` has no methods. – user4581301 Jun 02 '22 at 05:42
  • I cant change any of these classes. I just have the pointer only – Dipender Siwach Jun 02 '22 at 05:49
  • Looks like you'll need a mapping to match pointers to types then. – user4581301 Jun 02 '22 at 05:53
  • Does this answer your question? [Find out Type of C++ Void Pointer](https://stackoverflow.com/questions/1718412/find-out-type-of-c-void-pointer) – Caduchon Jun 02 '22 at 06:01
  • No @Caduchon, Every answer there is confusing and I am not able to understand it – Dipender Siwach Jun 02 '22 at 07:42
  • Replace the `void*` with `std::variant`. – Goswin von Brederlow Jun 02 '22 at 14:16
  • General rule of thumb: In C++ there's almost always a better solution than type erasure. Outside of extremely rare edge cases, the only time you should use `void *` is when calling into a C-Style interface. When you think you've found one of the edge cases, think again because it probably isn't. – user4581301 Jun 02 '22 at 16:48

1 Answers1

0

I do that using a common mother class :

class Base {};
class A : public Base {};
class B : public Base {};

Base* ptr = nullptr;
ptr = some_magical_function();
assert(ptr);
if(typeid(*ptr) == typeid(A))
{
  A& a = static_cast<A&>(*ptr);
  // work with a as an instance of A
}
else if(typeid(*ptr) == typeid(B))
{
  B& b = static_cast<B&>(*ptr);
  // work with b as an instance of B
}
else
  assert(false);

Concerning your second question, no you can not access to a class of any type from a void pointer without cast.

Caduchon
  • 4,574
  • 4
  • 26
  • 67