Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <memory>
- using namespace std;
- class GameObject
- {
- public:
- virtual void onContact(GameObject* otherObject)
- {
- cout << "object met object" << endl;
- }
- };
- class Crate;
- class Wall;
- class Hero;
- class Crate: public GameObject
- {
- public:
- virtual void onContact(Wall* w)
- {
- cout << "crate met wall" << endl;
- }
- virtual void onContact(Hero* h)
- {
- cout << "crate met hero" << endl;
- }
- };
- class Wall: public GameObject
- {
- public:
- virtual void onContact(Crate* c)
- {
- cout << "wall met crate" << endl;
- }
- virtual void onContact(Hero* h)
- {
- cout << "wall met hero" << endl;
- }
- };
- class Hero: public GameObject
- {
- public:
- virtual void onContact(Crate* crate)
- {
- cout << "hero met crate" << endl;
- }
- virtual void onContact(Wall* w)
- {
- cout << "hero met wall" << endl;
- }
- };
- int main()
- {
- //Works
- auto hero = unique_ptr<Hero>(new Hero());
- auto crate = unique_ptr<Crate>(new Crate());
- auto wall = unique_ptr<Wall>(new Wall());
- hero->onContact(crate.get()); // "hero met crate"
- hero->onContact(wall.get()); // "hero met wall"
- crate->onContact(wall.get()); // "crate met wall"
- wall->onContact(crate.get()); // "wall met crate"
- cout << endl;
- //Problem: in the program the game objects are stored in a vector (homogeneous container)
- vector<unique_ptr<GameObject>> gameObjects;
- gameObjects.push_back(move(hero));
- gameObjects.push_back(move(crate));
- gameObjects.push_back(move(wall));
- /*
- "object met object".
- Should be "hero met crate".
- That's because all objects in vector are GameObject.
- */
- gameObjects[0]->onContact(gameObjects[1].get());
- /* "object met object", should be "wall met crate" */
- gameObjects[2]->onContact(gameObjects[1].get());
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement