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

  1. //Polymorphic Bad Guy
  2. //Demonstrates calling member functions dynamically
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. class Enemy
  9. {
  10. public:
  11.     Enemy(int damage = 10);
  12.     virtual ~Enemy();
  13.     void virtual Attack() const;
  14.     
  15. protected:
  16.     int* m_pDamage;
  17. };
  18.  
  19. Enemy::Enemy(int damage)
  20. {
  21.     m_pDamage = new int(damage);
  22. }
  23.  
  24. Enemy::~Enemy()               
  25. {
  26.     cout << "In Enemy destructor, deleting m_pDamage.\n";
  27.     delete m_pDamage;
  28.     m_pDamage = 0;
  29. }
  30.  
  31. void Enemy::Attack() const
  32. {
  33.     cout << "An enemy attacks and inflicts " << *m_pDamage << " damage points.";
  34. }  
  35.  
  36. class Boss : public Enemy
  37. {
  38. public:
  39.     Boss(int multiplier = 3); 
  40.     virtual ~Boss();
  41.     void virtual Attack() const;
  42.     
  43. protected:
  44.     int* m_pMultiplier; 
  45. };
  46.  
  47. Boss::Boss(int multiplier)
  48. {
  49.     m_pMultiplier = new int(multiplier);
  50. }
  51.  
  52. Boss::~Boss()                 
  53. {
  54.     cout << "In Boss destructor, deleting m_pMultiplier.\n";
  55.     delete m_pMultiplier;
  56.     m_pMultiplier = 0;
  57.  
  58. void Boss::Attack() const
  59. {
  60.     cout << "A boss attacks and inflicts " << (*m_pDamage) * (*m_pMultiplier)
  61.          << " damage points.";
  62.  
  63. int main()
  64. {
  65.     cout << "Calling Attack() on Boss object through pointer to Enemy:\n";
  66.     Enemy* pBadGuy = new Boss();
  67.     pBadGuy->Attack();
  68.    
  69.     cout << "\n\nDeleting pointer to Enemy:\n";
  70.     delete pBadGuy;
  71.     pBadGuy = 0;
  72.    
  73.     return 0;
  74. }
  75.