13

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.

Eclipse
  • 44,851
  • 20
  • 112
  • 171
okami
  • 2,093
  • 7
  • 28
  • 40

2 Answers2

27

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
  • 44,851
  • 20
  • 112
  • 171
  • 1
    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 Aug 31 '10 at 02:48
  • ok. But just a quesiton under my question. Why should I keep virtual ~Base(){}; to dynamic_cast doesn't give me an error? – okami Aug 31 '10 at 02:58
  • @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 Aug 31 '10 at 03:49
4
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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
Taran9
  • 69
  • 1
  • 1
  • 4