fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class base
  5. {
  6. public:
  7. virtual base& downcast()
  8. {
  9. cout << "Downcast-base" << endl;
  10. return *this;
  11. }
  12. };
  13.  
  14. class derived: public base
  15. {
  16. public:
  17. virtual derived& downcast()
  18. {
  19. cout << "Downcast-derived" << endl;
  20. return *this;
  21. }
  22. };
  23.  
  24. void foo(const base& a)
  25. {
  26. cout << "base" << endl;
  27. }
  28.  
  29. void foo(const derived& a)
  30. {
  31. cout << "derived" << endl;
  32. }
  33.  
  34. int main()
  35. {
  36. base* ptr1 = new(base);
  37. base* ptr2 = new(derived);
  38.  
  39. foo(ptr1->downcast());
  40. foo(ptr2->downcast());
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Downcast-base
base
Downcast-derived
base