Created
October 5, 2011 01:19
-
-
Save FranklinChen/1263372 to your computer and use it in GitHub Desktop.
C++ abuse: simple example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// C++ abuse | |
#include <iostream> | |
using namespace std; | |
class Animal { | |
public: | |
virtual void food() = 0; | |
virtual void sound() = 0; | |
}; | |
class Dog : public Animal { | |
public: | |
void food() { cout << "Alpo" << endl; } | |
void sound() { cout << "Woof!" << endl; } | |
}; | |
class Cat : public Animal { | |
public: | |
void food() { cout << "Purina" << endl; } | |
void sound() { cout << "Meow!" << endl; } | |
}; | |
void transmigrate(void *dest, void *src) { | |
*(void **)dest = *(void **)src; | |
} | |
void brain_damage(void *obj) { | |
void *t = **((void ***)obj); | |
**((void ***)obj) = *(*((void ***)obj)+1); | |
*(*((void ***) obj)+1) = t; | |
} | |
// What does this program output and why? | |
int main() { | |
Dog *dog = new Dog(); | |
Cat *cat = new Cat(); | |
dog->food(); | |
transmigrate(dog, cat); | |
dog->food(); | |
brain_damage(dog); | |
dog->food(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something I wrote up back in the 1990s when I was first learning C++ and trying to understand it.