rtti1.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // rtti1.cpp -- using the RTTI dynamic_cast operator
  2. #include <iostream>
  3. #include <cstdlib>
  4. #include <ctime>
  5. using std::cout;
  6. class Grand
  7. {
  8. private:
  9. int hold;
  10. public:
  11. Grand(int h = 0) : hold(h) {}
  12. virtual void Speak() const { cout << "I am a grand class!\n";}
  13. virtual int Value() const { return hold; }
  14. };
  15. class Superb : public Grand
  16. {
  17. public:
  18. Superb(int h = 0) : Grand(h) {}
  19. void Speak() const {cout << "I am a superb class!!\n"; }
  20. virtual void Say() const
  21. { cout << "I hold the superb value of " << Value() << "!\n";}
  22. };
  23. class Magnificent : public Superb
  24. {
  25. private:
  26. char ch;
  27. public:
  28. Magnificent(int h = 0, char c = 'A') : Superb(h), ch(c) {}
  29. void Speak() const {cout << "I am a magnificent class!!!\n";}
  30. void Say() const {cout << "I hold the character " << ch <<
  31. " and the integer " << Value() << "!\n"; }
  32. };
  33. Grand * GetOne();
  34. int main()
  35. {
  36. std::srand(std::time(0));
  37. Grand * pg;
  38. Superb * ps;
  39. for (int i = 0; i < 5; i++)
  40. {
  41. pg = GetOne();
  42. pg->Speak();
  43. if( ps = dynamic_cast<Superb *>(pg))
  44. ps->Say();
  45. }
  46. // std::cin.get();
  47. return 0;
  48. }
  49. Grand * GetOne() // generate one of three kinds of objects randomly
  50. {
  51. Grand * p;
  52. switch( std::rand() % 3)
  53. {
  54. case 0: p = new Grand(std::rand() % 100);
  55. break;
  56. case 1: p = new Superb(std::rand() % 100);
  57. break;
  58. case 2: p = new Magnificent(std::rand() % 100,
  59. 'A' + std::rand() % 26);
  60. break;
  61. }
  62. return p;
  63. }