c++constantsdynamic-castconst-cast

Can not use dynamic_cast to a const object


I want to write a method where a Base object pointer will be passed as a parameter, and inside the method it will be casted to derived object pointer.

void func( const Base* const obj){
    Derived* der = dynamic_cast<Derived*>(obj);
}

But it shows error because dynamic cast cannot cast away const specifier. But I am not understanding why const specifier has to be removed here, all I am doing is creating a derived pointer which should point to some offset amount after the base pointer. I also tried const Derived* const der = dynamic_cast<Derived*>(obj);, but no result.

It is important to pass the parameter as const. How can I do this? Do I have to do it in the ugly way of first applying const_cast then dynamic_cast? is there any better way?


Solution

  • You're casting away const because you didn't do this:

    const Derived* der = dynamic_cast<const Derived*>(obj);
    

    If you actually need a Derived* then you need to

    Derived* der = dynamic_cast<Derived*>(const_cast<ObjType*>(obj));