fork download
  1. #include <cstdlib>
  2. #include <ctime>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. struct Item
  7. {
  8. Item(const std::string& name) : _name(name) {}
  9. std::string getName() const { return _name; }
  10.  
  11. virtual ~Item() {}
  12.  
  13. private:
  14. std::string _name;
  15. };
  16.  
  17. struct Weapon : public Item
  18. {
  19. Weapon(const std::string& name, int damage) : Item(name), _damage(damage) {}
  20.  
  21. void setDamage(int dam) { _damage = dam; }
  22. int getDamage() const { return _damage; }
  23.  
  24. private:
  25.  
  26. int _damage;
  27. };
  28.  
  29. struct Special : public Item
  30. {
  31. Special(const std::string& name, const std::string& otherProperty)
  32. : Item(name), _other(otherProperty) {}
  33.  
  34. std::string getOther() const { return _other; }
  35.  
  36. private:
  37. std::string _other;
  38. };
  39.  
  40. int main()
  41. {
  42. std::srand(std::time(0));
  43.  
  44. for (unsigned i = 0; i < 10; ++i)
  45. {
  46. Item* iptr;
  47. switch (std::rand() % 3)
  48. {
  49. case 0: iptr = new Weapon("Axe", 6); break;
  50. case 1: iptr = new Special("Deodorant", "Feminine"); break;
  51. case 2: iptr = new Item("Generic"); break;
  52. default: std::cout << "Unexpected value encountered\n"; return 0;
  53. }
  54.  
  55. // how do we know what we've got here? Is it a Special? A Weapon? Just a generic Item?
  56. if (Weapon* w = dynamic_cast<Weapon*>(iptr))
  57. {
  58. std::cout << "We have a weapon with name: " << w->getName();
  59. std::cout << "\nand damage: " << w->getDamage() << '\n';
  60. }
  61. else if (Special* s = dynamic_cast<Special*>(iptr))
  62. {
  63. std::cout << "We have a special with name: " << s->getName();
  64. std::cout << "\nand property: " << s->getOther() << '\n';
  65. }
  66. else
  67. std::cout << "We have an item with name: " << iptr->getName() << '\n';
  68.  
  69. delete iptr;
  70. }
  71. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
We have an item with name: Generic
We have a special with name: Deodorant
and property: Feminine
We have a special with name: Deodorant
and property: Feminine
We have a special with name: Deodorant
and property: Feminine
We have a special with name: Deodorant
and property: Feminine
We have an item with name: Generic
We have a weapon with name: Axe
and damage: 6
We have a special with name: Deodorant
and property: Feminine
We have a special with name: Deodorant
and property: Feminine
We have a special with name: Deodorant
and property: Feminine