C++ inheritance downcasting

Viewed 62492

I have my base class as follows:

class point    //concrete class
{
 ...    //implementation
}

class subpoint : public point  //concrete class
{
...     //implementation
}

How do I cast from a point object to a subpoint object? I have tried all three of the following:

point a;
subpoint* b = dynamic_cast<subpoint*>(&a);
subpoint* b = (subpoint*)a;
subpoint b = (subpoint)a;

What is wrong with these casts?

7 Answers

I know this is an old (nearly ten year old) question, but I ran into this same issue recently.

I'm not sure what the original poster's intention was, but there can be a case where you want to have a base class that you derive subclasses from, and these subclasses only provide methods which act differently from each other, and utilize the same base data, without adding any of their own data elements.

If you need to do this (for some reason), and want to be able to downcast a base/parent object to a child that was originally instantiated as a parent, then you do not want to use virtual methods, as they will work against you, and you will always be forced to use the virtual methods of the class that was instantiated, and no amount of casting will call the child methods.

So, this can certainly be done. It's just not considered to be "safe". Also, you cannot use dynamic_cast here, it must be a static_cast.

Related