avr39ripe

cppVirtualFunctionBasics

Aug 12th, 2021
1,065
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. class BaseA
  4. {
  5. public:
  6.     int valA;
  7. public:
  8.     BaseA() : valA { 1 } { std::cout << "BaseA DEFAULT ctor\n"; }
  9.     BaseA(int valAP) : valA{valAP} { std::cout << "BaseA ctor valA\n"; }
  10.     ~BaseA() { std::cout << "BaseA dtor\n"; }
  11.     void info() { std::cout << "I'm BaseA\n"; }
  12. };
  13.  
  14.  
  15. class Child : public BaseA
  16. {
  17. protected:
  18.     int childVal;
  19. public:
  20.     Child() : BaseA{111}, childVal{ 3 } { std::cout << "Child DEFAULT ctor\n"; }
  21.     Child(int childValP) : childVal{ childValP } { std::cout << "ChildA ctor childValP\n"; }
  22.     ~Child() { std::cout << "Child dtor\n"; }
  23.     void info() { BaseA::info(); std::cout << "I'm Child\n"; }
  24. };
  25.  
  26.  
  27. class Animal
  28. {
  29.     std::string name;
  30. public:
  31.     Animal(std::string nameP) : name{ nameP } {}
  32.     void sayHello()const { sound(); std::cout << " Hello, I'm " << name << '\n'; }
  33.     virtual void sound()const = 0;/*{ std::cout << "??????"; }*/
  34. };
  35.  
  36. class Cat : public Animal
  37. {
  38. public:
  39.     Cat(std::string nameP) : Animal{ nameP } {}
  40.     virtual void sound()const override{ std::cout << "Meow!"; }
  41. };
  42.  
  43. class Dog : public Animal
  44. {
  45. public:
  46.     Dog(std::string nameP) : Animal{ nameP } {}
  47.     virtual void sound()const override{ std::cout << "RRwaFF!"; }
  48. };
  49.  
  50. class Parrot : public Animal
  51. {
  52. public:
  53.     Parrot(std::string nameP) : Animal{ nameP } {}
  54.     virtual void sound()const override{ std::cout << "KrrrrAA!"; }
  55. };
  56.  
  57. void introduce(const Animal& animal)
  58. {
  59.     animal.sayHello();
  60. }
  61.  
  62. //void introduce(const Cat& animal)
  63. //{
  64. //    animal.sound(); std::cout << " Hello, I'm " << animal.name << '\n';
  65. //}
  66. //
  67. //void introduce(const Dog& animal)
  68. //{
  69. //    animal.sound(); std::cout << " Hello, I'm " << animal.name << '\n';
  70. //}
  71. //
  72. //void introduce(const Parrot& animal)
  73. //{
  74. //    animal.sound(); std::cout << " Hello, I'm " << animal.name << '\n';
  75. //}
  76.  
  77. int main()
  78. {
  79.     Animal* animals[]{ new Cat{ "Murzik" }, new Dog {"Rex"}, new Parrot { "Kesha" } };
  80.  
  81.     /*Cat cat{ "Murzik" };
  82.     Dog dog{"Rex"};
  83.     Parrot parrot{ "Kesha" };*/
  84.  
  85.  
  86.     //cat.sound(); std::cout << '\n';
  87.     //dog.sound(); std::cout << '\n';
  88.     //parrot.sound(); std::cout << '\n';
  89.  
  90.     /*introduce(cat);
  91.     introduce(dog);
  92.     introduce(parrot);*/
  93.  
  94.     for (const auto& animal : animals) { animal->sayHello(); }
  95. }
  96.  
RAW Paste Data