D
Deepak
Hi all,
I am trying to create a union consisting of objects whose classes have
default constructors, destructors etc. The compiler however doesn't
allow me to do that, the reason I believe for that being that when i
have multiple objects present in the union, it gets confused as to
whose constructor to call.
One way I got around that was to wrap those objects with anonymous
structs. I was wondering if this was a standard way of doing it or if
this is stupid and there is another way of getting around this
problem.
A simple example
#include <iostream>
#include <string> // This class has a default constructor and
// destructor defined
using namespace std;
union Key
{
string keyId; // Generates compiler error since default constructor
// is invoked
string keyType; // Generates compiler error since default
// constructor is invoked
};
int main ()
{
// Do something
return 0;
};
Now if i declare the union this way
union Key
{
struct{
string keyId;
};
struct{
string keyType;
};
};
There is no problem and i can access keyId and keyType as if theres
nothing wrong.
I'd really appricate if someone could throw some light on this subject
and educate me on the standard practice.
Thanks a lot for reading.
};
I am trying to create a union consisting of objects whose classes have
default constructors, destructors etc. The compiler however doesn't
allow me to do that, the reason I believe for that being that when i
have multiple objects present in the union, it gets confused as to
whose constructor to call.
One way I got around that was to wrap those objects with anonymous
structs. I was wondering if this was a standard way of doing it or if
this is stupid and there is another way of getting around this
problem.
A simple example
#include <iostream>
#include <string> // This class has a default constructor and
// destructor defined
using namespace std;
union Key
{
string keyId; // Generates compiler error since default constructor
// is invoked
string keyType; // Generates compiler error since default
// constructor is invoked
};
int main ()
{
// Do something
return 0;
};
Now if i declare the union this way
union Key
{
struct{
string keyId;
};
struct{
string keyType;
};
};
There is no problem and i can access keyId and keyType as if theres
nothing wrong.
I'd really appricate if someone could throw some light on this subject
and educate me on the standard practice.
Thanks a lot for reading.
};