fork download
  1. #include <iostream>
  2.  
  3. struct B
  4. {
  5. int type;
  6. int val;
  7. B(int v) : type(0), val(v) {}
  8. B(int t, int v) : type(t), val(v) {};
  9. };
  10.  
  11. struct D1 : public B
  12. {
  13. D1(int v) : B(1, v) {}
  14. void add100() { val += 100; }
  15. };
  16.  
  17. struct D2 : public B
  18. {
  19. D2(int v) : B(2, v) {}
  20. void mul100() { val *= 100; }
  21. };
  22.  
  23. void f(B &b)
  24. {
  25. using namespace std;
  26.  
  27. cout << "pre = " << b.val << endl;
  28. switch (b.type) {
  29. case 1:
  30. static_cast<D1 &>(b).add100(); // downcast
  31. break;
  32. case 2:
  33. static_cast<D2 &>(b).mul100(); // downcast
  34. break;
  35. }
  36. cout << "post = " << b.val << endl;
  37. }
  38.  
  39. int main(int argc, char **argv) {
  40. D1 d1(11);
  41. f(d1);
  42.  
  43. D2 d2(22);
  44. f(d2);
  45. return 0;
  46. }
  47.  
  48.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
pre  = 11
post = 111
pre  = 22
post = 2200