fork download
  1. #include <iostream>
  2. #include <ostream>
  3.  
  4. using namespace std;
  5.  
  6. struct Example
  7. {
  8. virtual void virtualfunction()=0;
  9. virtual ~Example() {}
  10. };
  11.  
  12. struct Implmenetation : Example
  13. {
  14. bool alive;
  15. Implmenetation() : alive(true) {}
  16. void virtualfunction()
  17. {
  18. cout << "Implmenetation::virtualfunction alive=" << alive << endl;
  19. }
  20. ~Implmenetation()
  21. {
  22. alive=false;
  23. cout << "Implmenetation::~Implmenetation" << endl;
  24. }
  25. };
  26.  
  27. struct Forwarder : Example
  28. {
  29. Example *impl;
  30. Forwarder(Example *i) : impl(i) {}
  31. void virtualfunction()
  32. {
  33. impl->virtualfunction();
  34. }
  35. };
  36.  
  37. void codeIDontControl(Example *ex)
  38. {
  39. ex->virtualfunction();
  40. delete ex;
  41. }
  42.  
  43. void myCode()
  44. {
  45. Implmenetation impl;
  46.  
  47. codeIDontControl(new Forwarder(&impl));
  48. //do something with ex //doesn't work because ex has been freed
  49. impl.virtualfunction();
  50. }
  51. int main()
  52. {
  53. myCode();
  54. }
  55.  
Success #stdin #stdout 0.02s 2816KB
stdin
Standard input is empty
stdout
Implmenetation::virtualfunction alive=1
Implmenetation::virtualfunction alive=1
Implmenetation::~Implmenetation