fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class Pet
  7. {
  8. protected:
  9. string type;
  10. string name;
  11. public:
  12. Pet(const string& arg1, const string& arg2);
  13. virtual void whoAmI() const;
  14. virtual string speak() const = 0;
  15. };
  16.  
  17. Pet::Pet(const string& arg1, const string& arg2): type(arg1), name(arg2)
  18.  
  19.  
  20. {}
  21. void Pet::whoAmI() const
  22. {
  23. cout << "I am an excellent " << type << " and you may refer to me as " << name << endl;
  24. }
  25.  
  26. class Dog : public Pet
  27. {
  28. public:
  29. using Pet::Pet;
  30. void whoAmI() const override { std::cout << "Dog::whoAmI\n";} // override the describe() function
  31. string speak() const override;
  32.  
  33. };
  34.  
  35. string Dog::speak() const
  36. {
  37. return "Arf!";
  38. }
  39.  
  40. class Cat : public Pet
  41. {
  42. public:
  43. using Pet::Pet;
  44.  
  45. string speak() const override;
  46. // Do not override the whoAmI() function
  47. };
  48.  
  49. string Cat::speak() const
  50. {
  51. return "Meow!";
  52. }
  53.  
  54. ostream& operator<<(ostream& out, const Pet& p)
  55. {
  56. p.whoAmI();
  57. out << "I say " << p.speak();
  58. return out;
  59. }
  60.  
  61. int main()
  62. {
  63. Dog spot("dog","Spot");
  64. Cat socks("cat","Socks");
  65. Pet* ptr = &spot;
  66. cout << *ptr << endl;
  67. ptr = &socks;
  68. cout << *ptr << endl;
  69. }
  70.  
Success #stdin #stdout 0s 4412KB
stdin
Standard input is empty
stdout
Dog::whoAmI
I say Arf!
I am an excellent cat and you may refer to me as Socks
I say Meow!