fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <string>
  4. #include <memory>
  5. using namespace std;
  6.  
  7. class Animal {
  8. public:
  9. virtual void speak() = 0;
  10. virtual ~Animal() {}; // Always a good thing if the class has virtual members
  11. string name;
  12. };
  13.  
  14. class Dog : public Animal {
  15. public:
  16. Dog(string n) { this->name = n; }
  17. void speak() { cout << this->name << " says WOOF!" << endl; }
  18. };
  19.  
  20. class AnimalQueue {
  21. std::list<Animal*> animals;
  22. public:
  23. void enqueue(Animal* a) {
  24. animals.push_back(a); // Copy the pointer
  25. }
  26. Animal* dequeue() {
  27. Animal *d = animals.front();
  28. animals.pop_front(); // Destroy the pointer
  29. return d;
  30. }
  31. };
  32.  
  33. int main() {
  34. AnimalQueue q;
  35. std::unique_ptr<Dog> d = std::make_unique<Dog>("Rex");
  36. q.enqueue(d.get()); // This will now store the pointer to the object
  37.  
  38. // Try with dog-specific command
  39. Animal *sameDog = q.dequeue(); // d.get() and sameDog are now pointing at the same object
  40. if (d.get() == sameDog)
  41. std::cout << "d.get() == sameDog" << std::endl;
  42. std::cout << sameDog->name << std::endl;// Prints "Rex"
  43. sameDog->speak();
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
d.get() == sameDog
Rex
Rex says WOOF!