Below I have defined a union and declared a string variable in it. As expected, the compiler doesn't allow the declaration of its object because it has a string variable, which is basically dynamically allocated and we can not guess the size of the union due to this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
usingnamespace std;
union node
{
string a;
int b;
};
int main()
{
node obj;
getchar();
return 0;
}
Now, instead of string, I have used a char pointer in the same code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
usingnamespace std;
union node
{
char *a;
int b;
};
int main()
{
node obj;
obj.a = newchar[50];
delete[]obj.a;
getchar();
return 0;
}
and compiler allows its execution...
but why?
From what I understand, string is also nothing but a char pointer which allocates new memory depending upon the size of the string you give it to. So, why does it not allow string in a union but does allow a char pointer, which is basically the same thing? (or is it not?)
Why are you using something as messy as a union in C++?
> From what I understand, string is also nothing but a char pointer which allocates
> new memory depending upon the size of the string you give it to
But it also has constructors and destructors that the compiler arranges to call on your behalf.
Just doing obj.b = 0 completely screws up any possibility of correctly using obj.a for anything at all.
> but why?
Because you're now in control of the lifetimes of any dynamic resources.