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?
a
can't be made into asubpoint
. that implementation isn't there.The purpose of a dynamic cast is to "check at run time if an object is of a certain type in the hierarchy". So now let's look at what you have:
By contrast, this would have worked:
The fact that you attempt to do them. A
point
is not asubpoint
, I'd be surprised if it worked.Overall, this will not work because
point
is not asubpoint
; only the reverse is true. However, there are other issues as well.In order:
dynamic_cast
only works on polymorphic types, i.e., types that declare at least one virtual function. My guess is thatpoint
has no virtual functions, which means it cannot be used withdynamic_cast
.For this cast to work,
point
needs to declare a conversion operator tosubpoint *
, e.g.,point::operator subpoint *()
.For this cast to work, point needs to declare a conversion operator to
subpoint
orsubpoint
needs to have a constructor that takes a parameter convertable frompoint
.For the first example,
dynamic_cast
only works if there's at least one virtual method in the base class. And if the object isn't actually of the type you're trying to cast, it will result in NULL.For the second example you need
&a
instead ofa
, but once you've fixed that you'll get undefined behavior because the object type is wrong.The third example requires an
operator subpoint()
method inpoint
to do a conversion while creating a copy.You can't; unless either
point
has a conversion operator, orsubpoint
has a conversion constructor, in which case the object types can be converted with no need for a cast.You could cast from a
point
reference (or pointer) to asubpoint
reference (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 ifa
doesn't refer to asubpoint
, then usingb1
will have undefined behaviour.The second (
dynamic_cast
) is safer, but will only work ifpoint
is polymorphic (that is, if it has a virtual function). Ifa
refers to an object of incompatible type, then it will throw an exception.