views:

48

answers:

2

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.

+3  A: 

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.

Eclipse
I tried it doesn't work.
okami
You need the const twice - once in the type of the variable being assigned to, and once in the `dynamic_cast`. In the example of what you tried, you only had the first one.
Eclipse
ok. But just a quesiton under my question.Why should I keep virtual ~Base(){}; to dynamic_cast doesn't give me an error?
okami
@okami: You could substitute it with any virtual function, provided you didn't actually need a virtual destructor. See this: http://publib.boulder.ibm.com/infocenter/compbgpl/v9v111/index.jsp?topic=/com.ibm.xlcpp9.bg.doc/language_ref/keyword_dynamic_cast.htm "The dynamic_cast operator uses the runtime type information generated from polymorphic classes". Also, this, on whether you should keep the virtual destructor: http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7
Merlyn Morgan-Graham
A: 
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.

Taran9
Edited to add code tags.
DeadMG