4

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?

Leigh
  • 12,038
  • 4
  • 28
  • 36
Rakib
  • 7,435
  • 7
  • 29
  • 45

2 Answers2

11

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));
marceloow
  • 117
  • 9
Donnie
  • 45,732
  • 10
  • 64
  • 86
8

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);
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489