home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter10 / overriding_boss.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2006-11-02  |  1.5 KB  |  71 lines

  1. //Overriding Boss
  2. //Demonstrates calling and overriding base member functions
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. class Enemy
  9. {
  10. public:
  11.     Enemy(int damage = 10);
  12.     void virtual Taunt() const;     //made virtual to be overridden
  13.     void virtual Attack() const;    //made virtual to be overridden
  14.  
  15. private:
  16.     int m_Damage;
  17. };
  18.  
  19. Enemy::Enemy(int damage): 
  20.     m_Damage(damage)
  21. {}
  22.  
  23. void Enemy::Taunt() const
  24. {
  25.     cout << "The enemy says he will fight you.\n";
  26. }  
  27.  
  28. void Enemy::Attack() const
  29. {
  30.     cout << "Attack! Inflicts " << m_Damage << " damage points.";
  31. }
  32.  
  33. class Boss : public Enemy
  34. {
  35. public:
  36.     Boss(int damage = 30);
  37.     void virtual Taunt() const;      //optional use of keyword virtual
  38.     void virtual Attack() const;     //optional use of keyword virtual
  39. };
  40.  
  41. Boss::Boss(int damage): 
  42.     Enemy(damage)            //call base class constructor with argument
  43. {}
  44.  
  45. void Boss::Taunt() const     //override base class member function
  46. {
  47.     cout << "The boss says he will end your pitiful existence.\n";
  48. }  
  49.  
  50. void Boss::Attack() const    //override base class member function
  51. {
  52.     Enemy::Attack();         //call base class member function 
  53.     cout << " And laughs heartily at you.\n";
  54. }   
  55.  
  56. int main()
  57. {
  58.     cout << "Enemy object:\n";
  59.     Enemy anEnemy;
  60.     anEnemy.Taunt();
  61.     anEnemy.Attack();
  62.  
  63.     cout << "\n\nBoss object:\n";
  64.     Boss aBoss;
  65.     aBoss.Taunt();
  66.     aBoss.Attack(); 
  67.       
  68.     return 0;
  69. }
  70.  
  71.