fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. class Item{
  7. public:
  8. virtual ~Item() {}
  9. };
  10.  
  11. class Armor : public Item{
  12. };
  13.  
  14. void equipArmor(shared_ptr<Item> item){ //Armor class argument
  15. shared_ptr<Armor> a = dynamic_pointer_cast<Armor>(item);
  16. if (a) {
  17. cout << "Armor"<<endl;
  18. }
  19. else cout << "Item"<<endl;
  20.  
  21. }
  22.  
  23. int main(){
  24. vector<shared_ptr<Item>> items;
  25. shared_ptr<Item> a = make_shared<Armor>();
  26. items.push_back(a);
  27. shared_ptr<Item> i = make_shared<Item>();
  28. items.push_back(i);
  29.  
  30. equipArmor(items[0]); //Call function with an "Item" as an argument (even though it is in fact also an "Armor")
  31. equipArmor(items[1]); //Call function with an "Item" as an argument (even though it is in fact also an "Armor")
  32. }
  33.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Armor
Item