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.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Comments are closed, but trackbacks and pingbacks are open.