Skip to content

Instantly share code, notes, and snippets.

@FranklinChen
Created October 5, 2011 01:19
Show Gist options
  • Save FranklinChen/1263372 to your computer and use it in GitHub Desktop.
Save FranklinChen/1263372 to your computer and use it in GitHub Desktop.
C++ abuse: simple example
// 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();
}
@FranklinChen
Copy link
Author

Something I wrote up back in the 1990s when I was first learning C++ and trying to understand it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment