<p>I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.</p>

<pre><code>MyClass *m = (MyClass *)ptr;
</code></pre>

<p>all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?</p>

<pre><code>MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast&lt;MyClass *&gt;(ptr);
MyClass *m = dynamic_cast&lt;MyClass *&gt;(ptr);
</code></pre>

[{'answer_id': 28020, 'author': 'Inisheer', 'author_id': 2982, 'author_profile': 'https://Stackoverflow.com/users/2982', 'pm_score': 4, 'selected': False, 'text': '<p><code>dynamic_cast</code> has runtime type checking and only works with references and pointers, whereas <code>static_cast</code> does not offer runtime type checking. For complete information, see the MSDN article <em><a href="http://msdn.microsoft.com/en-us/library/c36yw7x9(VS.80).aspx" rel="noreferrer">static_cast Operator</a></em>.</p>\n'}, {'answer_id': 28026, 'author': 'TJ Seabrooks', 'author_id': 3022, 'author_profile': 'https://Stackoverflow.com/users/3022', 'pm_score': 7, 'selected': False, 'text': '<p>You should look at the article <em><a href="http://en.wikibooks.org/wiki/C%2B%2B_Programming/Programming_Languages/C%2B%2B/Code/Statements/Variables/Type_Casting" rel="noreferrer">C++ Programming/Type Casting</a></em>.</p>\n\n<p>It contains a good description of all of the different cast types. The following taken from the above link:</p>\n\n<blockquote>\n  <p>const_cast</p>\n  \n  <p>const_cast(expression) The const_cast&lt;>() is used to add/remove\n  const(ness) (or volatile-ness) of a variable.</p>\n  \n  <p>static_cast</p>\n  \n  <p>static_cast(expression) The static_cast&lt;>() is used to cast between\n  the integer types. \'e.g.\' char->long, int->short etc.</p>\n  \n  <p>Static cast is also used to cast pointers to related types, for\n  example casting void* to the appropriate type.</p>\n  \n  <p>dynamic_cast</p>\n  \n  <p>Dynamic cast is used to convert pointers and references at run-time,\n  generally for the purpose of casting a pointer or reference up or down\n  an inheritance chain (inheritance hierarchy).</p>\n  \n  <p>dynamic_cast(expression)</p>\n  \n  <p>The target type must be a pointer or reference type, and the\n  expression must evaluate to a pointer or reference. Dynamic cast works\n  only when the type of object to which the expression refers is\n  compatible with the target type and the base class has at least one\n  virtual member function. If not, and the type of expression being cast\n  is a pointer, NULL is returned, if a dynamic cast on a reference\n  fails, a bad_cast exception is thrown. When it doesn\'t fail, dynamic\n  cast returns a pointer or reference of the target type to the object\n  to which expression referred.</p>\n  \n  <p>reinterpret_cast</p>\n  \n  <p>Reinterpret cast simply casts one type bitwise to another. Any pointer\n  or integral type can be casted to any other with reinterpret cast,\n  easily allowing for misuse. For instance, with reinterpret cast one\n  might, unsafely, cast an integer pointer to a string pointer.</p>\n</blockquote>\n'}, {'answer_id': 28052, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 4, 'selected': False, 'text': "<p>C-style casts conflate const_cast, static_cast, and reinterpret_cast.</p>\n\n<p>I wish C++ didn't have C-style casts.  C++ casts stand out properly (as they should; casts are normally indicative of doing something bad) and properly distinguish between the different kinds of conversion that casts perform.  They also permit similar-looking functions to be written, e.g. boost::lexical_cast, which is quite nice from a consistency perspective.</p>\n"}, {'answer_id': 28054, 'author': 'Jason Baker', 'author_id': 2147, 'author_profile': 'https://Stackoverflow.com/users/2147', 'pm_score': 5, 'selected': False, 'text': '<p>FYI, I believe Bjarne Stroustrup is quoted as saying that C-style casts are to be avoided and that you should use static_cast or dynamic_cast if at all possible.</p>\n\n<p><a href="http://www.stroustrup.com/bs_faq2.html" rel="noreferrer">Barne Stroustrup\'s C++ style FAQ</a></p>\n\n<p>Take that advice for what you will.  I\'m far from being a C++ guru.</p>\n'}, {'answer_id': 103914, 'author': 'ugasoft', 'author_id': 10120, 'author_profile': 'https://Stackoverflow.com/users/10120', 'pm_score': 5, 'selected': False, 'text': "<p>Avoid using C-Style casts.</p>\n\n<p>C-style casts are a mix of const and reinterpret cast, and it's difficult to find-and-replace in your code. A C++ application programmer should avoid C-style cast.</p>\n"}, {'answer_id': 1255015, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 12, 'selected': True, 'text': "<h2>static_cast</h2>\n<p><code>static_cast</code> is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. <code>static_cast</code> performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:</p>\n<pre><code>void func(void *data) {\n  // Conversion from MyClass* -&gt; void* is implicit\n  MyClass *c = static_cast&lt;MyClass*&gt;(data);\n  ...\n}\n\nint main() {\n  MyClass c;\n  start_thread(&amp;func, &amp;c)  // func(&amp;c) will be called\n      .join();\n}\n</code></pre>\n<p>In this example, you know that you passed a <code>MyClass</code> object, and thus there isn't any need for a runtime check to ensure this.</p>\n<h2>dynamic_cast</h2>\n<p><code>dynamic_cast</code> is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a <code>bad_cast</code> exception is thrown in that case).</p>\n<pre><code>if (JumpStm *j = dynamic_cast&lt;JumpStm*&gt;(&amp;stm)) {\n  ...\n} else if (ExprStm *e = dynamic_cast&lt;ExprStm*&gt;(&amp;stm)) {\n  ...\n}\n</code></pre>\n<p>You can <strong>not</strong> use <code>dynamic_cast</code> for downcast (casting to a derived class) <strong>if</strong> the argument type is not polymorphic. For example, the following code is not valid, because <code>Base</code> doesn't contain any virtual function:</p>\n<pre><code>struct Base { };\nstruct Derived : Base { };\nint main() {\n  Derived d; Base *b = &amp;d;\n  dynamic_cast&lt;Derived*&gt;(b); // Invalid\n}\n</code></pre>\n<p>An &quot;up-cast&quot; (cast to the base class) is always valid with both <code>static_cast</code> and <code>dynamic_cast</code>, and also without any cast, as an &quot;up-cast&quot; is an implicit conversion (assuming the base class is accessible, i.e. it's a <code>public</code> inheritance).</p>\n<h2>Regular Cast</h2>\n<p>These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering <code>dynamic_cast</code>. Needless to say, this is much more powerful as it combines all of <code>const_cast</code>, <code>static_cast</code> and <code>reinterpret_cast</code>, but it's also unsafe, because it does not use <code>dynamic_cast</code>.</p>\n<p>In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the &quot;equivalent&quot; <code>static_cast</code> sequence would give you a compile-time error for that.</p>\n<p>Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.</p>\n"}, {'answer_id': 9151168, 'author': 'larsmoa', 'author_id': 167251, 'author_profile': 'https://Stackoverflow.com/users/167251', 'pm_score': 4, 'selected': False, 'text': '<p><code>dynamic_cast</code> only supports pointer and reference types. It returns <code>NULL</code> if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, <code>dynamic_cast</code> can be used to check if an object is of a given type, <code>static_cast</code> cannot (you will simply end up with an invalid value).</p>\n\n<p>C-style (and other) casts have been covered in the other answers. </p>\n'}, {'answer_id': 18414172, 'author': 'Hossein', 'author_id': 2736559, 'author_profile': 'https://Stackoverflow.com/users/2736559', 'pm_score': 8, 'selected': False, 'text': '<h2>Static cast</h2> \n \nThe static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.\n<pre><code>char c = 10;       // 1 byte\nint *p = (int*)&amp;c; // 4 bytes\n</code></pre>\n<p>Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.</p>\n<pre><code>*p = 5; // run-time error: stack corruption\n</code></pre>\n<p>In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.</p>\n<pre><code>int *q = static_cast&lt;int*&gt;(&amp;c); // compile-time error\n</code></pre>\n<h2>Reinterpret cast</h2>\n<p>To force the pointer conversion, in the same way as the C-style cast does in the background, the reinterpret cast would be used instead.</p>\n<pre><code>int *r = reinterpret_cast&lt;int*&gt;(&amp;c); // forced conversion\n</code></pre>\n<p>This cast handles conversions between certain unrelated types, such as from one pointer type to another incompatible pointer type. It will simply perform a binary copy of the data without altering the underlying bit pattern. Note that the result of such a low-level operation is system-specific and therefore not portable. It should be used with caution if it cannot be avoided altogether.</p>\n<h2>Dynamic cast</h2>\n<p>This one is only used to convert object pointers and object references into other pointer or reference types in the inheritance hierarchy. It is the only cast that makes sure that the object pointed to can be converted, by performing a run-time check that the pointer refers to a complete object of the destination type. For this run-time check to be possible the object must be polymorphic. That is, the class must define or inherit at least one virtual function. This is because the compiler will only generate the needed run-time type information for such objects.</p>\n<p><strong>Dynamic cast examples</strong></p>\n<p>In the example below, a <code>MyChild</code> pointer is converted into a <code>MyBase</code> pointer using a dynamic cast. This derived-to-base conversion succeeds, because the Child object includes a complete Base object.</p>\n<pre><code>class MyBase \n{ \n  public:\n  virtual void test() {}\n};\nclass MyChild : public MyBase {};\n\n\n\nint main()\n{\n  MyChild *child = new MyChild();\n  MyBase  *base = dynamic_cast&lt;MyBase*&gt;(child); // ok\n}\n</code></pre>\n<p>The next example attempts to convert a <code>MyBase</code> pointer to a <code>MyChild</code> pointer. Since the Base object does not contain a complete Child object this pointer conversion will fail. To indicate this, the dynamic cast returns a null pointer. This gives a convenient way to check whether or not a conversion has succeeded during run-time.</p>\n<pre><code>MyBase  *base = new MyBase();\nMyChild *child = dynamic_cast&lt;MyChild*&gt;(base);\n\n \nif (child == 0) \nstd::cout &lt;&lt; &quot;Null pointer returned&quot;;\n</code></pre>\n<p>If a reference is converted instead of a pointer, the dynamic cast will then fail by throwing a <code>bad_cast</code> exception. This needs to be handled using a <code>try-catch</code> statement.</p>\n<pre><code>#include &lt;exception&gt;\n// …  \ntry\n{ \n  MyChild &amp;child = dynamic_cast&lt;MyChild&amp;&gt;(*base);\n}\ncatch(std::bad_cast &amp;e) \n{ \n  std::cout &lt;&lt; e.what(); // bad dynamic_cast\n}\n</code></pre>\n<h2>Dynamic or static cast</h2>\n<p>The advantage of using a dynamic cast is that it allows the programmer to check whether or not a conversion has succeeded during run-time. The disadvantage is that there is a performance overhead associated with doing this check. For this reason using a static cast would have been preferable in the first example, because a derived-to-base conversion will never fail.</p>\n<pre><code>MyBase *base = static_cast&lt;MyBase*&gt;(child); // ok\n</code></pre>\n<p>However, in the second example the conversion may either succeed or fail. It will fail if the <code>MyBase</code> object contains a <code>MyBase</code> instance and it will succeed if it contains a <code>MyChild</code> instance. In some situations this may not be known until run-time. When this is the case dynamic cast is a better choice than static cast.</p>\n<pre><code>// Succeeds for a MyChild object\nMyChild *child = dynamic_cast&lt;MyChild*&gt;(base);\n</code></pre>\n<p>If the base-to-derived conversion had been performed using a static cast instead of a dynamic cast the conversion would not have failed. It would have returned a pointer that referred to an incomplete object. Dereferencing such a pointer can lead to run-time errors.</p>\n<pre><code>// Allowed, but invalid\nMyChild *child = static_cast&lt;MyChild*&gt;(base);\n \n// Incomplete MyChild object dereferenced\n(*child);\n</code></pre>\n<h2>Const cast</h2>\n<p>This one is primarily used to add or remove the <code>const</code> modifier of a variable.</p>\n<pre><code>const int myConst = 5;\nint *nonConst = const_cast&lt;int*&gt;(&amp;myConst); // removes const\n</code></pre>\n<p>Although <code>const</code> cast allows the value of a constant to be changed, doing so is still invalid code that may cause a run-time error. This could occur for example if the constant was located in a section of read-only memory.</p>\n<pre><code>*nonConst = 10; // potential run-time error\n</code></pre>\n<p><code>const</code> cast is instead used mainly when there is a function that takes a non-constant pointer argument, even though it does not modify the pointee.</p>\n<pre><code>void print(int *p) \n{\n   std::cout &lt;&lt; *p;\n}\n</code></pre>\n<p>The function can then be passed a constant variable by using a <code>const</code> cast.</p>\n<pre><code>print(&amp;myConst); // error: cannot convert \n                 // const int* to int*\n \nprint(nonConst); // allowed\n</code></pre>\n<p><a href="https://web.archive.org/web/20140104001826/http://www.pvtuts.com/cpp/cpp-type-conversion-ii" rel="noreferrer">Source and More Explanations</a></p>\n'}]
['https://Stackoverflow.com/questions/28002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1821/']