Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
Rakib Avatar asked Dec 02 '22 16:12

Rakib


2 Answers

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));
like image 141
Donnie Avatar answered Dec 07 '22 23:12

Donnie


What you cannot do is remove the const qualifier with a dynamic_cast. If the types are polymorphic (have at least one virtual function) you should be able to do:

const Derived *der = dynamic_cast<const Derived*>(obj);
like image 42
David Rodríguez - dribeas Avatar answered Dec 08 '22 00:12

David Rodríguez - dribeas