Skip to content

Instantly share code, notes, and snippets.

@tux21b
Created May 29, 2012 17:34
Show Gist options
  • Save tux21b/2829656 to your computer and use it in GitHub Desktop.
Save tux21b/2829656 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <typeinfo>
struct Game;
struct Command
{
void execute(Game& game);
};
struct Game
{
Command cmd;
virtual void run() {
cmd.execute(*this);
}
};
struct Chess : public Game
{
};
void Command::execute(Game &game) {
try {
Chess &chess = dynamic_cast<Chess&>(game);
std::cout << "Chess Objekt" << std::endl;
} catch (std::bad_cast &ex) {
std::cout << "Kein Chess Objekt" << std::endl;
}
}
int main() {
Game *game = new Game();
game->run(); // Ausgabe: Kein Chess Objekt
std::cout << "aber:" << std::endl;
Chess *chess = new Chess();
chess->run(); // Ausgabe: Chess Objekt
std::cout << "bzw.:" << std::endl;
Game *game2 = new Chess();
game2->run(); // Ausgabe: Chess Objekt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment