difference between static_cast and dynamic_cast

You may see those guru programmers often use static_cast and dynamic_cast which are mysterious to you because you only use the implicit cast or C style explicit cast. So what is the difference between  static_cast and dynamic_cast?

To upcast a child class pointer to a parent class pointer, there is no difference at all between them. But if you downcast a parent class pointer to a child class pointer, you should have a virtual function in the parent class, otherwise dynamic_cast will get a compiling error:

error: cannot dynamic_cast ‘pa’ (of type ‘class A*’) to type ‘class B*’ (source type is not polymorphic)

static_cast compiles without error. Even there is a virtual function in the parent class to make compiling successful, the run-time result is different. static_cast gets a normal pointer while dynamic_cast gets a null pointer. Note that for upcast, dynamic_cast does not need a virtual function existing in the child class or parent class.

Comments are closed, but trackbacks and pingbacks are open.