Is this not downcasting?
-
02-10-2019 - |
Question
If I do
double d = 34.56;
int i = (int)d;
Am I not "downcasting"?
OR
Is this term only used in terms of classes and objects?
I am confused because in this case we are "downcasting" from a bigger double
to a smaller int
, but in case of classes, we "downcast" from a smaller base class
to a bigger derived class
.
Aren't these two conventions, in some sense, opposite?
Solution
No, you are not down casting. You are just casting, and you're chopping off anything after the decimal.
Down casting doesn't apply here. The primitives int
and double
are not objects in C++ and are not related to each other in the way two objects in a class hierarchy are. They are separate and primitive entities.
Down casting refers to the act of casting one object into another object that derives from it. It refers to the act of moving down from the root of the class hierarchy. It has nothing to do with the sizes of types in question.
OTHER TIPS
Downcasting is the act of casting a reference of a base class to one of its derived classes.
http://en.wikipedia.org/wiki/Downcasting
No, you do not downcast, since double and int are not classes.
int
and double
are both primitives and not classes, so the concepts of classes don't apply to them.
Yes, it is a conversion from a "larger" to a "smaller" type (in terms of numerical size), but it's just a "cast" and not a "downcast"
The two aren't so much opposite as simply unrelated. In the example case, we're taking a value of one type, and the cast takes that and produces a similar value of a type that's vaguely similar, but completely unrelated.
In the case of traversing an inheritance tree with something like dynamic_cast
, we're taking a pointer (or reference) to an object, and having previously decided to treat it as a pointer to some other type of object, we're basically (attempting to) treat it as (something closer to) the original type of object again. In particular, however, we're not creating a new or different value at all -- we're simply creating a different view of the same value (i.e., the same actual object).
You aren't casting -- you're converting. Different thing entirely.