fork(1) download
  1. #include <iostream>
  2. #include <list>
  3. #include <string>
  4. using namespace std;
  5.  
  6. class Animal {
  7. public:
  8. virtual void speak() = 0;
  9. virtual ~Animal() {}; // Always a good thing if the class has virtual members
  10. string name;
  11. };
  12.  
  13. class Dog : public Animal {
  14. public:
  15. Dog(string n) { this->name = n; }
  16. void speak() { cout << this->name << " says WOOF!" << endl; }
  17. };
  18.  
  19. class AnimalQueue {
  20. list<Dog> dogs;
  21. public:
  22. void enqueue(Animal* a) {
  23. Dog * d = dynamic_cast<Dog*>(a);
  24. dogs.push_back(*d); // This creates a copy of d and stores it
  25. }
  26. Dog dequeueDog() {
  27. Dog d = dogs.front(); // This creates a copy of the front element
  28. dogs.pop_front();
  29. return d;
  30. }
  31. };
  32.  
  33. int main() {
  34. // Set up
  35. AnimalQueue q;
  36. Dog * d;
  37. d = new Dog("Rex");
  38. q.enqueue(d);
  39.  
  40. // Try with dog-specific command
  41. *d = q.dequeueDog();
  42. cout << d->name << endl;// Prints "Rex"
  43. d->speak();
  44.  
  45. delete d; // Free your memory
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
Rex
Rex says WOOF!