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.
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.
Const casts are only available in C++.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With