Type Safety - Examples

Examples

The following simple C++ program illustrates that C++ permits operations that are type-unsafe:

#include using namespace std; int main { int ival = 5; // A four-byte integer (on most processors) void *pval = &ival; // Store the address of ival in an untyped pointer double dval = *((double*)pval); // Convert it to a double pointer and get the value at that address cout << dval << endl; // Output the double (this will be garbage and not 5!) return 0; }

Even 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.

#include using namespace std; class Parent {}; class Child1 : public Parent { public: int a; }; class Child2 : public Parent { public: double b; }; int main { Child1 c1; c1.a = 5; Child2 c2; c2.b = 2.4; Parent *p = &c1; // Down-conversion is safe Child1 *pc1 = (Child1*)p; // Up-conversion is not safe cout << pc1->a << endl; // ...but this time it's okay p = &c2; // Safe pc1 = (Child1*)p; // Not safe cout << pc1->a << endl; // This time it breaks! return 0; }

The 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 people’s 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 (1688–1744)

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)