/* C++ unsafe type casting */ using namespace std; #include class A { private: int x; public: A() { x = 2; } int getx() { return x; } }; class B { private: double y; int x; public: B() { x = 4; y = 3.5; } double gety() { return y; } }; int main() { B *b = new B(); A *a = (A*)b; // casting allowed despite no inheritance relationship cout << a->getx() << endl; // another problem: A *a2 = new A(); B *b2 = (B*) a2; // allowed in C++ !!! cout << b2->gety() << endl; // prints something unpredictable // Yikes! how did an A object suddenly become a B object? The // B object contains info (double y) that's not in the A object. // Where did get that information from? Thin air? Actually, // it gets it from whatever is "supposed" to be in the right memory // location, which may belong to an entirely different program. // In fact (no joke), viruses have been introduced this way. return 0; }