Examples
The following simple C++ program illustrates that C++ permits operations that are type-unsafe:
#includeEven though pval does contain the correct address of ival, when pval is cast from a void pointer to a double pointer the resulting double value is not 5, but an undefined garbage value. On the machine code level, this program has explicitly prevented the processor from performing the correct conversion from a four-byte integer to an eight-byte floating-point value. When the program is run it will output a garbage floating-point value and possibly raise a memory exception. Thus, C++ (and C) allow type-unsafe code.
The next example shows a slightly more complex type safety issue in C++ involving object pointer conversion.
#includeThe two child classes have members of different types. When a pointer to a less-specific parent class is converted to a pointer to a more-specific child class, the resulting pointer may or may not point to a valid object of its type. In the first conversion, the pointer is valid, and in the second, it is not. Again, a garbage value is printed and a memory exception may be raised.
Read more about this topic: Type Safety
Famous quotes containing the word examples:
“It is hardly to be believed how spiritual reflections when mixed with a little physics can hold peoples attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.”
—G.C. (Georg Christoph)
“Histories are more full of examples of the fidelity of dogs than of friends.”
—Alexander Pope (16881744)
“No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.”
—André Breton (18961966)