fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <memory> // **** added
  5.  
  6. class Object
  7. {
  8. protected:
  9. std::string name;
  10. int id;
  11. int value;
  12.  
  13.  
  14. public:
  15. virtual ~Object() // **** needs to be virtual
  16. {
  17. }
  18.  
  19. virtual void Display() const // made const-correct
  20. {
  21.  
  22. }
  23.  
  24. };
  25.  
  26. class Weapon : public Object
  27. {
  28. private:
  29. int damage;
  30. float speed;
  31.  
  32.  
  33. public:
  34. Weapon(std::string newName, int newValue, int newDamage, float newSpeed)
  35. {
  36. name = newName;
  37. value = newValue;
  38. damage = newDamage;
  39. speed = newSpeed;
  40. }
  41.  
  42. /****
  43. ~Weapon() // **** implicitly overridden
  44. {
  45. }
  46. ****/
  47.  
  48. void Display() const override // ****
  49. {
  50. std::cout << "Name: " << name << std::endl;
  51. std::cout << "Value: " << value << std::endl;
  52. std::cout << "Damage: " << damage << std::endl;
  53. std::cout << "Speed: " << speed << std::endl;
  54.  
  55. }
  56.  
  57. };
  58.  
  59. int main()
  60. {
  61. std::vector< std::shared_ptr<Object> > inventory; // modified
  62.  
  63. //Weapon BronzeDagger("Bronze Dagger", 5, 1, 1); // ****
  64. //inventory.push_back(BronzeDagger); // **** modified
  65. inventory.push_back( std::make_shared<Weapon>( "Bronze Dagger", 5, 1, 1 ) ) ; // ****
  66. inventory.push_back( std::make_shared<Weapon>( "Golden Sword", 500, 10, 2 ) ) ; // ****
  67.  
  68. // for(int i = 0; i < inventory.size(); i++) // ****
  69. for( auto p : inventory )
  70. {
  71. //inventory[i].Display(); // ****
  72. p->Display();
  73. std::cout << '\n' ;
  74. }
  75. }
  76.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
Name: Bronze Dagger
Value: 5
Damage: 1
Speed: 1

Name: Golden Sword
Value: 500
Damage: 10
Speed: 2