fork download
  1. #include <iostream>
  2. #include <typeinfo>
  3.  
  4. struct A
  5. {
  6. virtual ~A() {}
  7. virtual int get_it() const { return i ; }
  8. int i = 3 ;
  9. };
  10.  
  11. struct B : A
  12. {
  13. virtual int get_it() const override { return A::get_it() + j ; }
  14. int j = 5 ;
  15. };
  16.  
  17. int foo( const A& a ) { return a.get_it() ; }
  18.  
  19. int bar( const A& a )
  20. {
  21. int result = a.i ;
  22.  
  23. try
  24. {
  25. const B& b = dynamic_cast< const B& >(a) ;
  26. result += b.j ;
  27. }
  28. catch( const std::bad_cast& ) { /* this is not a B */ }
  29.  
  30. return result ;
  31. }
  32.  
  33. int main()
  34. {
  35. A a ;
  36. std::cout << foo(a) << ' ' << bar(a) << '\n' ;
  37.  
  38. B b ;
  39. std::cout << foo(b) << ' ' << bar(b) << '\n' ;
  40.  
  41. }
  42.  
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
3 3
8 8