Compile-time and runtime casting c?

The compiler considers only the static types. The runtime checks the dynamic (runtime) type. Looking at your examples.

Upcasts can be checked at compile time - the type system guarantees that the cast succeeds. Downcasts cannot (in general) be checked at compile time, so they are always checked at runtime. Unrelated types cannot be cast to each other.

The compiler considers only the static types. The runtime checks the dynamic (runtime) type. Looking at your examples: Other x = new Other(); Derived d = (Derived)x; The static type of x is Other.

This is unrelated to Derived so the cast fails at compile time. Base x = new Base(); Derived d = (Derived)x; The static type of x is now Base. Something of type Base might have dynamic type Derived, so this is a downcast.In general the compiler can't know from the static type of x if it the runtime type is Base, Derived, of some other subclass of Base.

So the decision of whether the cast is allowed is left to the runtime.

If your variable is of Base type, is can be theoretically constructed by Derived constructor, thus being a variable of Derived type actually. At compile time, compiler does not bother itself with trying to figure out whether in each particular case such downcast (representing a variable of Base type as an entity of Derived type) is possible. Your sample is simple - you create a new class and cast it right away.

But what if you get Base from somewhere else, e.g. , some method call? Compiler just cannot "guess" what your method is going to return and therefore throw on not throw an error. When you cast Other, compiler sees that there is no possibility that Other is actually Derived and throws an exception.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions