title: C++: Union Destructor
body: <p>A union is a user-defined data or class type that, at any given time, contains only one object from its list of members. Suppose all the possible candidate members are needed to be allocated dynamically. For Eg.</p>
  
  <pre><code>// Union Destructor
  #include &lt;string&gt;
  using namespace std;
  
  union Person
  {
  private:
      char* szName;
      char* szJobTitle;
  public:
      Person() : szName (nullptr), szJobTitle (nullptr) {}
      Person (const string&amp; strName, const string&amp; strJob)
      {
          szName = new char[strName.size()];
          strcpy (szName, strName.c_str());
  
          szJobTitle = new char [strJob.size()];
          strcpy (szJobTitle, strJob.c_str());    // obvious, both fields points at same location i.e. szJobTitle
      }
      ~Person()   // Visual Studio 2010 shows that both szName and szJobTitle
      {           // points to same location.
          if (szName) {
              delete[] szName;     // Program crashes here.
              szName = nullptr;  // to avoid deleting already deleted location(!)
          }
          if (szJobTitle)
              delete[] szJobTitle;
      }
  };
  
  int main()
  {
      Person you ("your_name", "your_jobTitle");
      return 0;
  }
  </code></pre>
  
  <p>Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?).</p>
  
  <p>What will be the correct implementation for the destructor?</p>
  
  <p>Same way, how to destruct a class object, if my class contains an union member (<a href="https://stackoverflow.com/q/16025132/2243384">how to wrtie destructor for class including a Union</a>)?</p>