What is the difference between static cast vs dynamic cast vs regular cast? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 5

What is the difference between static cast vs dynamic cast vs regular cast?

11th Oct 2017, 10:47 PM
Vijay
Vijay - avatar
1 Respuesta
+ 1
Static cast is done at compile time and there is no overhead. If the cast is not possible you get a compile erro. Ex: cast an int to a double. Dynamic cast is done at runtime and is usually (always?) used in the context of polymorphism. Ex: cast an Animal pointer to a Dog pointer when you know that what is really being pointed is a Dog object. If it is not a Dog you get an exception during runtime. There's also the reinterpret cast, which is more low level and should only be used when really needed. It means "take these bits and treat it as if it were this type". The other cast is the C style cast, which should be avoided in C++. It is somewhat equivalent to trying the different casts until one works, including reinterpreted cast.
14th Jan 2018, 1:53 PM
Darlan Cavalcante Moreira
Darlan Cavalcante Moreira - avatar