dynamic_cast static _cast

       Reprinted from https://blog.csdn.net/fyyyr/article/details/79217808

 A is the base class and B is the derived class. Now define:

 

[cpp]  view plain copy  
  1. A* pA  
  2.   
  3. B*   pB; 

In general, pB can be converted to pA, (the pointer or reference of the derived class is converted into the base class representation) , which is called up-conversion.

But the opposite is generally not possible, that is, converting pA to pB, (converting a base class pointer or reference to a derived class representation) , which is called down conversion. It is wrong to do this behavior directly with (* class name ) .

However, down-conversion is not absolutely impossible. To downcast, two keywords are used: dynamic_cast and static_cast .

1. The keyword static_cast is relatively simple.

The format is: static_cast  <  type-id > (  expression  )

This will convert expression to type-id .

Note that type-id must be a pointer or reference, and expression must be consistent with the type of type-id (both pointers or references).

But the static_cast keyword does not perform runtime type checking. So static_cast is safe for upcasting, but unsafe for downcasting.

2.      Keyword dynamic_cast

The format is: dynamic_cast  <  type-id > ( expression )

This will convert expression to type-id .

Note that the type-id must be a pointer or a reference, and the expression must be the same type as the type -id ( both pointers or references ) .

The dynamic_cast keyword does runtime type checking. So dynamic_cast is safe for both up-conversion and down-conversion.

However, a necessary condition for using dynamic_cast is that there must be a virtual function in the base class A. And static_cast has no such restriction. The reason is: there is a virtual function in the class, it means that it wants to make the base class pointer or reference point to the derived class object, and the conversion is meaningful at this time.

①      dynamic_cast supports cross conversion

Base class A has two directly derived classes B and C.

Then, converting B* pB to C* pC, this conversion from derived class B to derived class C is called cross conversion.

Only dynamic_cast can be used in this case .

②      dynamic_cast supports multiple inheritance

There are two base classes A1 and A2, and the derived class B is derived from A1 and A2.

Then, to convert pB to pA1 or pA2, only dynamic_cast can be used at this time , static_cast cannot realize this function.

That is: in the case of single inheritance, the effect of dynamic_cast and static _cast is the same; in the case of multiple inheritance, only dynamic_cast can be used .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325739522&siteId=291194637