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?
You can’t; unless either
pointhas a conversion operator, orsubpointhas a conversion constructor, in which case the object types can be converted with no need for a cast.You could cast from a
pointreference (or pointer) to asubpointreference (or pointer), if the referred object were actually of typesubpoint:The first (
static_cast) is more dangerous; there is no check that the conversion is valid, so ifadoesn’t refer to asubpoint, then usingb1will have undefined behaviour.The second (
dynamic_cast) is safer, but will only work ifpointis polymorphic (that is, if it has a virtual function). Ifarefers to an object of incompatible type, then it will throw an exception.