code_junkie

a better way than casting from a base class to derived class

Nov 13th, 2011
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. Base * bases[NUM_ITEMS];
  2. for(int i=0; i<NUM_ITEMS; i++) {
  3. int r = get_random_integer();
  4. if(r == 0)
  5. bases[i] = new Derived1;
  6. else if(r == 1)
  7. bases[i] = new Derived2;
  8. // ...
  9. }
  10.  
  11. shared_ptr<Base> bases[NUM_ITEMS];
  12. for(int i=0; i<NUM_ITEMS; i++) {
  13. int r = get_random_integer();
  14. if(r == 0)
  15. bases[i].reset(new Derived1);
  16. else if(r == 1)
  17. bases[i].reset(new Derived2);
  18. // ...
  19. }
  20.  
  21. std::vector< shared_ptr<Base> > bases;
  22. for(int i=0; i<NUM_ITEMS; i++) {
  23. int r = get_random_integer();
  24. if(r == 0)
  25. bases.push_back(shared_ptr<Base>(new Derived1));
  26. else if(r == 1)
  27. bases.push_back(shared_ptr<Base>(new Derived2));
  28. // ...
  29. }
  30.  
  31. Derived1 * d = &dynamic_cast<Derived1&>(*bases[x]);
  32.  
  33. shared_ptr<Derived1> d = dynamic_pointer_cast<Derived1>(bases[x]);
  34. if(d) {
  35. // conversion successful, it pointed to a derived. d and bases[x] point still
  36. // to the same object, thus share it.
  37. }
  38.  
  39. interface IShape
  40. {
  41. double GetArea();
  42. }
  43.  
  44. class Square : IShape
  45. {
  46. double GetArea()
  47. {
  48. return sideLengh*sideLength;
  49. }
  50. ...
  51. }
  52.  
  53. class FunnyShape : IShape
  54. {
  55. //do funny stuff
  56. ...
  57. }
  58.  
  59. ...
  60.  
  61. void calcTotalArea(List<IShape> shapes)
  62. {
  63. double total = 0.0;
  64. foreach (IShape s in shapes)
  65. {
  66. total += s.GetArea();
  67. }
  68. return total;
  69. }
  70.  
  71. class bankAccount
  72. {
  73. int money;
  74. bankAccount() {};
  75.  
  76. int MoneyInAccount() {return money;};
  77. }
  78.  
  79. class savingsAccount : public bankAccount
  80. {
  81. int SavingsInterest();
  82. }
  83.  
  84. class MoneyMarket : public bankAccount
  85. {
  86. int CalculateAllPastReturns();
  87. }
Add Comment
Please, Sign In to add comment