I would like to know how to solve this problem. I don’t understand what this question is asking me:
dynamic_cast<Y>(new X)
- To Be legal?
- To probably succeed?
I would like to know how to solve this problem. I don’t understand what this question is asking me:
dynamic_cast<Y>(new X)
The question should be:
What can you say about the definitions of
X
andY
so that the following code is legal, and furthermore that the cast succeeds?
Then the answer is fairly straight-forward: X
has to be a complete type for the new
expression to be legal. Dynamic casts are valid for upcasting to a non-virtual base, so if Y
is a pointer to a non-virtual base (possibly CV-qualified, and including a pointer to X
itself), the cast is valid and succeeds.
Moreover, there are other valid uses of dynamic casts on polymorphic types (i.e. classes with virtual functions). If X
is polymorphic, then Y
may be void *
, or Y
may be a pointer to any other class in the inheritance hierarchy of X
. However, the cast will only succeed if Y
is a pointer to a base (however, this base may be virtual!).
(The reasoning for the present is simpler than for an arbitrary dynamic cast, since we already know the dynamic type of the castee. In general, dynamic casts can do far more complicated things.)
First, to be legal, Y
must be a pointer type. So let's
rewrite the question as dynamic_cast<Y
cv_qualifiers*>( new X )
. Having done this, it's
legal if X
is a complete class type, and if either X
is a
polymorphic type, or Y
is the same type as X
or is a base
class of X
.
It will succeed if Y
is the same as X
, or is a base class of
X
. Note that in these cases, dynamic_cast
has the same
behavior as static_cast
, and in fact corresponds to an
implicit conversion, so one would normally just write new X
,
without any cast. (There are a few special cases where the cast
might be necessary, typically when passing the results to a void*
parameter. In such cases, I would prefer
static_cast
, but the semantics of the two are exactly the
same in this case.)
Finally, there is one special case (which will also succeed): if
X
is a polymorphic type, and Y
is void
cv_qualifiers *
. In this case, the dynamic_cast
does have different semantics than static_cast
, although
since the X*
returned from new X
will have the type
“pointer to most derived type”, the actual effect
will be identical (and again, the same as the implicit
conversion).
It's completely unanswerable without knowing Y and X. For example, if Y is int, then illegal. Else, if Y is a pointer to a polymorphic class, it might succeed, or it might not, but there's certainly nothing "probable" about it. Finally, this is a rather nasty memory leak.