Can a pointer of a derived class be type cast to the pointer of its base class?

前端 未结 4 573
粉色の甜心
粉色の甜心 2021-01-05 09:54

The pointer of derived class returned by new can be type cast to the pointer of its base class.

Is this true or false?

I know dynamic_cast can be used to cas

4条回答
  •  醉梦人生
    2021-01-05 10:26

    Your question is not clear becuse it mixes up several different things.

    On the one hand, a pointer to derived class can be converted to a pointer to a base class (assuming the base is accessible). This is a natural conversion and there's no need for any cast to do it.

    On the other hand, you mention dynamic_cast and its ability to to perform downcasts. But downcasts are casts in the opposite direction: from a pointer to a base class to a pointer to derived class. Downcasts can be performed by both dynamic_cast and static_cast depending on what you need and what amount of run-time checking you require.

    ... And at the same time you ar talking about casting the result of new, which, of course, can only be upcasted, but not downcasted.

    So, what is it you are asking about? Upcasts or downcasts?

提交回复
热议问题