Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast const Class using dynamic_cast

I want to cast this:

class Base 
{
public:
    virtual ~Base(){};
};
class Der : public Base {};

int main()
{
    const Base* base = new Der;
    Der* der = dynamic_cast<Der*>(base); // Error

    return 0;
}

What should I do? I tried to put: const Der* der = dynamic_cast<Der*>(base); to mantain the const but this doesn't work.

like image 927
okami Avatar asked Aug 31 '10 02:08

okami


People also ask

What is the use of dynamic_cast in C++?

The dynamic_cast operator ensures that if you convert a pointer to class A to a pointer to class B , the object of type A pointed to by the former belongs to an object of type B or a class derived from B as a base class subobject.

Can I cast Const in C?

Const casts are only available in C++.

Can you const static cast?

The static_cast operator cannot be used to cast away const. You can use static_cast to cast “down” a hierarchy (from a base to a derived pointer or reference), but the conversion is not checked; the result might not be usable. A static_cast cannot be used to cast down from a virtual base class.


2 Answers

Try this:

const Der* der = dynamic_cast<const Der*>(base);

dynamic_cast doesn't have the ability to remove a const qualifier. You can cast away const separately using a const_cast, but it's generally a bad idea in most situations. For that matter, if you catch yourself using dynamic_cast, it's usually a sign that there is a better way to do what you are trying to do. It's not always wrong, but think of it as a warning sign that you are doing things the hard way.

like image 59
Eclipse Avatar answered Sep 30 '22 05:09

Eclipse


const Der* der1 = dynamic_cast<const Der*>(base); 

Der* der2 = dynamic_cast<Der*>(const_cast<Base*>(base));

while both the above castings work, the second one should be avoided.

like image 24
Taran9 Avatar answered Sep 30 '22 06:09

Taran9