fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. union U {
  6. string s;
  7. int i;
  8. U (string s) : s(s) { cout << "s is active"<<endl;}
  9. U (int i) : i(i) { cout << "i is active"<<endl;}
  10. U() : s() { cout << "s is active by default" <<endl; }
  11. ~U() { cout << "delete... but what ?"<<endl; }
  12. };
  13.  
  14. int main() {
  15. U u("hello");
  16. u.s += ", world";
  17. cout << u.s <<endl;
  18. u.i=0; // ouch!!! this is not the active member : what happens to the string ?
  19. u.s="goodbye"; // thinks that s is an active valid string which is no longer the case
  20. //cout << u.s <<endl; // ouch !?
  21. return 0;
  22. }
Runtime error #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
s is active
hello, world