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.
// Union Destructor
#include <string>
using namespace std;
union Person
{
private:
char* szName;
char* szJobTitle;
public:
Person() : szName (nullptr), szJobTitle (nullptr) {}
Person (const string& strName, const string& 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;
}
Above program get crashed at 1st delete statement in ~Person (at moment when szName contains valid memory location, WHY?).
What will be the correct implementation for the destructor?
Same way, how to destruct a class object, if my class contains an union member (how to wrtie destructor for class including a Union)?