Changing the Type Pointed To

The static_cast operator is used to convert with a compile-time check, but not a runtime check, so this means that the pointers must be related. The void* pointer can be converted to any pointer, so the following compiles and makes sense:

    int *pi = static_cast<int*>(malloc(sizeof(int))); 
*pi = 42;
cout << *pi << endl;
free(pi);

The C malloc function returns a void* pointer so you have to convert it to be able to use the memory. (Of course, the C++ new operator removes the need for such casting.) The built-in types are not "related" enough for static_cast to convert between pointer types, so you cannot use static_cast to convert an int* pointer to a char* pointer, even though int and char are both integer types. For custom types that are related through inheritance, you can cast pointers using static_cast, but there is no runtime check that the cast is correct. To cast with runtime checks you should use dynamic_cast, and more details will be given in Chapters 4, Classes.

The reinterpret_cast operator is the most flexible, and dangerous, of the cast operators because it will convert between any pointer types without any type checks. It is inherently unsafe. For example, the following code initializes a wide character array with a literal. The array wc will have six characters, hello followed by NULL. The wcout object interprets a wchar_t* pointer as a pointer to the first character in a wchar_t string, so inserting wc will print the string (every character until the NUL). To get the actual memory location, you have to convert the pointer to an integer:

    wchar_t wc[] { L"hello" }; 
wcout << wc << " is stored in memory at ";
wcout << hex;
wcout << reinterpret_cast<int>(wc) << endl;

Similarly, if you insert a wchar_t into the wcout object, it will print the character, not the numeric value. So, to print out the codes for the individual characters, we need to cast the pointer to a suitable integer pointer. This code assumes that a short is the same size as a wchar_t:

    wcout << "The characters are:" << endl; 
short* ps = reinterpret_cast<short*>(wc);
do
{
wcout << *ps << endl;
} while (*ps++);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset