Const and static grouped

I have a reference to a child class type object that is passed as a const pointer of the parent class type. I need to overlay this pointer to a non-const child class.

Is there anything better than that static_cast<child*>(const_cast<parent*>(pParent))

?

+3


source to share


1 answer


If you know for sure that the passed pointer points to an object of the type child

or its subobject, use

static_cast<child const*>(pParent)

      



Note that this causes undefined (!) Behavior if the above condition is not met, so if there is a possibility that the pointer does not point to an object of the type child

but parent

is polymorphic, use dynamic_cast

with the same syntax. It will return a null pointer if the cast is invalid, defining the latter via RTTI.

0


source







All Articles