Conversion from void* to the pointer of the base class

前端 未结 4 1987
时光取名叫无心
时光取名叫无心 2020-12-05 21:01

I have some hierarchy: base, derived classes and some structure storing user data as void*. That void can store both Base and Derived classes pointers. Main problem that I d

4条回答
  •  没有蜡笔的小新
    2020-12-05 21:39

    If you know it's a derived pointer and you want to get a base pointer, you can do this:

    Base* d_restored_to_base = (Base*)(Derived*)derived_v;
    

    You will find that the Base* points to a different location than the Derived*, so the intermediary cast is required.

提交回复
热议问题