简体   繁体   中英

How to find which class's object a void pointer is pointing at (C++)? Can we access that class's methods using the same void pointer?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM