fork(4) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. struct NO_INIT {};
  7.  
  8. class Thing {
  9. int a;
  10. public:
  11. Thing(int v = 0): a (v) {}
  12. Thing(NO_INIT) {}
  13. virtual const char * type_name(){ return "Thing"; }
  14. virtual int value() { return a; }
  15. };
  16.  
  17. class OtherThing : public Thing {
  18. public:
  19. OtherThing(int v): Thing(v) {}
  20. OtherThing(NO_INIT ni): Thing(ni) {}
  21.  
  22. virtual const char * type_name() { return "Other Thing"; }
  23. };
  24.  
  25. template <typename TO_T>
  26. inline TO_T* turn_thing_to(Thing* p)
  27. {
  28. return ::new(p) TO_T(NO_INIT());
  29. }
  30.  
  31. int main() {
  32. Thing * thing = new Thing(42);
  33. std::cout << thing->type_name() << "\n";
  34. std::cout << thing->value() << "\n";
  35.  
  36. turn_thing_to<OtherThing>(thing);
  37. std::cout << thing->type_name() << "\n";
  38. std::cout << thing->value() << "\n";
  39. return 0;
  40. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
Thing
42
Other Thing
42