compile / runtime / casting

Hello, This may seem like a stupid question but I just want to make sure I understand. I am learning about casting, static cast and dynamic, and the video i am learning from says, static is compile time and dynamic is run time. Now I know that compile time, is the time when the source code is being changed to machine language and run time, is when the program is running. So does that mean, that the static cast has to be correct (cast-able?) before it will compile, but the dynamic cast will compile even if what I am casting is not possible/correct, and I will not find that out until the program is running?

So basically, static cast has to be something that can be cast to compile, but dynamic does not to compile? - but will end up with issues during run time with dynamic if wrong.
http://www.cplusplus.com/doc/oldtutorial/typecasting/ may help.

quoting from the above about dynamic casting:

The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.


So even though dynamic is checked at run time, it is ALSO checked as well as it can be at compile time, so if you do something drastically incorrect the compiler will catch it.

So you don't need to fear that you can compile a complete mess, but you do need to run your code and test it. If you stick to polymorphic items in dynamic casts, it should work. If you try to do something that should have been a reinterpret cast, it may not compile, and if it does, it may not work...

I don't know, is that what you were asking? There are PLENTY of screwy things that compile but won't run, you just have to be aware of them and always test carefully.

Casting is overly complicated and hard to get a handle on. Its worth spending some time on it to make sure you use the right one.
Last edited on
> but the dynamic cast will compile even if what I am casting is not possible/correct,
> and I will not find that out until the program is running?

That the dynamic_cast is syntactically correct is checked at compile time;

the evaluation of the result of the dynamic_cast cast is done at run-time; typically, the implementation uses runtime type information to make sure that it is a safe (correct) cast.
Topic archived. No new replies allowed.