From regines, 1 Year ago, written in Plain Text.
Embed
  1. #ifndef INHERITANCE_H_
  2. #define INHERITANCE_H_
  3. #include <iostream>
  4. using std::cout;
  5.  
  6. struct monster{
  7.         monster(){ cout << "a monster is bread\n"; }
  8.         ~monster(){ cout << "monster killed\n"; }
  9.         void health(){ cout << "immortal?\n"; }
  10.         virtual void attack(){ cout << "roar\n";}
  11. };
  12.  
  13. struct troll: monster {
  14.         troll(){ cout << "a troll grows\n";}
  15.         ~troll(){ cout << "troll petrified\n";}
  16.         void attack(){ swing_club();}
  17.         virtual void swing_club(){
  18.                 cout << "clubbing kills me\n";
  19.                 myhealth--;
  20.         }
  21.         void health (){ cout << "troll-health:"<< myhealth<<'\n';}
  22. protected:
  23.         int myhealth{10};
  24. };
  25.  
  26. struct forum_troll: troll {
  27.         forum_troll() :troll{}{ cout << "not quite a monster\n";}
  28.         ~forum_troll(){ cout << "troll banned\n";}
  29.         virtual void swing_club(){
  30.                 cout << "swinging is healthy\n";
  31.                 myhealth++;
  32.         }
  33.         void attack(){ cout << "write stupid things\n";}
  34. };
  35.  
  36. #endif /* INHERITANCE_H_ */
  37.  
  38. int main(){
  39.         cout << "a ------\n";
  40.         forum_troll ft{};
  41.         troll t{ft};
  42.         monster &m{ft};
  43.        
  44.         cout << "b ------\n";
  45.         ft.attack();
  46.         t.attack();
  47.         m.attack();
  48.        
  49.         cout << "c ------\n";
  50.         ft.swing_club();
  51.         t.swing_club();
  52.        
  53.         cout << "d ------\n";
  54.         ();
  55.         ();
  56.         ();
  57.        
  58.         cout << "end ------\n";
  59. } // ende main()
  60.