c++ - converting a base class pointer to a derived class pointer

前端 未结 3 1983
误落风尘
误落风尘 2021-01-31 09:02
#include 
using namespace std;

class Base {
public:
  Base() {};
  ~Base() {};
};

template
class Derived: public Base {
  T _val;
public         


        
3条回答
  •  面向向阳花
    2021-01-31 10:01

    Try this:

    Derived * d = static_cast* >(b);
    

    downside it is, that you can cast class that is instance of Base() and then d->raw() will be undefined (segmentation fault likley). If that can be case, use dynamic_cast and have at least one function ob base virtual (having destructors virtual is essential when working with polmorphism).

    Virtual functions are under the hood implemented using pointer on virtual table. This pointer can be also used to identify true type of class. This is used by dynamic_cast to check if this conversion can be done and brings small extra overhead when casted.

提交回复
热议问题