Jump to content

C++: Difference between revisions

319 bytes added ,  21 February 2022
Line 43: Line 43:
[https://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used Types of casts]
[https://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used Types of casts]


C++ has several types of casts.
C++ has several types of casts including:
These are the main ones you should use.
* [https://en.cppreference.com/w/cpp/language/static_cast <code>static_cast</code>] - your standard cast with conversion. Does not perform any checks.
* <code>static_cast</code>
* [https://en.cppreference.com/w/cpp/language/dynamic_cast <code>dynamic_cast</code>] - for casting objects with checking, requires a polymorphic base class (with a virtual function). Will return nullptr.
* <code>dynamic_cast</code>
* [https://en.cppreference.com/w/cpp/language/reinterpret_cast <code>reinterpret_cast</code>] - cast without any conversion, for directly dealing with binary data, equivalent to <code>*(T*)</code> in C.
If you're casting between things but do not want to change the bit-pattern (e.g. binary data or pointers), you can also use <code>reinterpret_cast</code>.


====References====
====References====