Introduction
Most programmers learn C before C , and get used to C style casting. When writing C , sometimes we may be confused about when to use static_cast <> and when to use reinterpret_cast <>. In this article, I will illustrate what static_cast <> Actually Does, And Will Show Some Cases That Will Lead To Errors.
Generic Types
Float f = 12.3;
Float * pf = & f;
// Static Cast <>
// ok, n = 12
INT n = static_cast
// error, Types Pointed to Are Unrelated
// int * pn = static_cast
// ok
Void * pv = static_cast
// ok, but * pn2 is Rubbish
INT * PN2 = static_cast
// ReinterPret_cast <>
// Error, The Compiler Know You Should
// Call Static_cast <>
// int i = reinterpret_cast
// ok, but * pn is actially rubbish, Same as * PN2
INT * PI = Reinterpret_cast
In Short, Static_Cast <> Will Try To Convert, E.G., float-to-integer, while reinterpret_cast <> simply changer That Compiler's Mind To Reconsider That Object As Another Type.
Pointer Types
Pointer Casting is a bit complicated, we will use the following classes for the rest of the the article:
Class CBasex
{
PUBLIC:
INT X;
CBasex () {x = 10;
Void foo () {Printf ("CBasex :: foo () x =% d / n", x);
}
Class CBasey
{
PUBLIC:
Int Y;
INT * PY;
CBasey () {y = 20; py = & y;}
Void bar () {Printf ("CBasey :: bar () y =% D, * py =% D / N", Y, * PY);
}
Class CDERIVED: PUBLIC CBASEX, PUBLIC CBASEY
{
PUBLIC:
Int z;
}
Case 1: Casting Between Unrelated Classes
// Convert Between CBasex * and cbasey *
CBasex * px = new cbasex ();
// error, Types Pointed to Are Unrelated
// CBasey * py1 = static_cast
// Compile OK, But Py2 Is Not CBasex
CBasey * py2 = reinterpret_cast
// system crash !!
// py2-> bar ();
As we learnt in the generic types example, static_cast <> will fail if you try to cast an object to another unrelated class, while reinterpret_cast <> will always succeed by "cheating" the compiler to believe that the object is really that unrelated class.
Case 2: Casting to Related Classes
CDERIVED * PD = New CDerived ();
2. Printf ("cderived * pd =% x / n", (int) PD);
3.
4. // static_cast <> cderived * -> cbesey * -> cderived *
// ok, implicit static_cast <> casting
5. CBasey * py1 = pd;
6. Printf ("CBasey * PY1 =% x / n", (int) py1);
// ok, now PD1 = PD
7. CDerived * pd1 = static_cast
8. Printf ("CDERIVED * PD1 =% x / n", (int) PD1);
9.
10. // ReinterPret_cast
// ok, but py2 is not cbesey *
11. CBasey * py2 = reinterpret_cast
12. Printf ("CBasey * PY2 =% x / n", (int) py2);
13.
14. // unrelated static_cast <>
15. CBasey * py3 = new cbasey ();
16. Printf ("CBasey * PY3 =% x / n", (int) py3);
// OK, Even Py3 IS Just A "New CBasey ()"
17. CDERIVED * PD3 = static_cast
18. Printf ("CDERIVED * PD3 =% x / n", (int) PD3);
---------------------- Output ---------------------------
CDERIVED * PD = 392fb8
CBasey * py1 = 392fbc
CDERIVED * PD1 = 392FB8
CBasey * py2 = 392fb8
CBasey * PY3 = 390FF0
CDERIVED * PD3 = 390FEC
Noted that when static_cast <> - ing CDerived * to CBaseY * (line 5), the result is CDerived * offset by 4. To know what static_cast <> is actually doing, we have to take a look at the memory layout of CDerived. Memory Layout of Cderived
As shown in the diagram, CDerived's memory layout contains two objects, CBaseX and CBaseY, and the compiler knows this. Therefore, when you cast CDerived * to CBaseY *, it adds the pointer by 4, and when you cast CBaseY to CDerived, it Subtracts the Pointer by 4. However, You Can do this even if it is not a cderived (line 14-18) [1].
Of Course, The Problem Happens Only You Have Multiple Inheritance. Static_cast <> and reinterpret_cast <> make no difference if you are casting cderived to cbeasex.
Case 3: Casting Back and Forth Between void *
Because Any Pointer Can Be Cast to Void *, And Void * Can Be Cast Back to Any Pointer (True For Both Static_cast <> and reinterpret_cast <>), Errors May Occur if not handled carefully.
CDERIVED * PD = new cderived ();
Printf ("cderived * pd =% x / n", (int) PD);
CBasey * py = pd; // ok, py = PD 4
Printf ("CBasey * py =% x / n", (int) py);
Void * pv1 = py; // ok, pv = py
Printf ("VOID * PV1 =% x / n", (int) PV1);
// pd2 = py, but we expect pd2 = py - 4
CDERIVED * PD2 = static_cast
Printf ("cderived * pd2 =% x / n", (int) PD2);
// system crash
// pd2-> bar ();
---------------------- Output ---------------------------
CDERIVED * PD = 392fb8
CBasey * py = 392fbc
Void * pv1 = 392fbc
CDERIVED * PD2 = 392FBC
Once We Have Cast The Pointer To Void *, We can't Cast It Back to the Original Class Easily. In The Above Example, The Only To Get Back a CDerived * from a void * is to cast it to a cbeasey * and THEN to CDERIVED *. But IF WE Are Not Sure WHETER IT IS CBASEY * OR CDERIVED *, THEN We Have to Use Dynamic_Cast <> or typeid [2] .footnote
dynamic_cast <>, on the other hand, can guard against casting a generic CBaseY * to CDerived *. dynamic_cast <> requires the classes to be "polymorphic", i.e., contains "virtual" function, and hence can not be void *.
References
[MSDN] C Language Reference - Casting Nishant Sivakumar, Casting Basics - USE C Casts in Your VC . Net Program Juan Soulie, C Language Tutorial: Type Casting
History
3 Feb 2006: Initial Version Uploaded.