It looks like one cannot have a std::string as a member of a union. The code compiles without the string on line 13.
cppreference wrote:
A union cannot have data members of reference types.
cppreference wrote:
The union is only as big as necessary to hold its largest data member. The other data members are allocated in the same bytes as part of that largest member.
The size of the string cannot be known, so that's why the compiler complains.
std::string has constructor and destructor so it is generally not safe storing it in a union. C++ will allow it if you add constructor and destructor for the union but then you need to explicitly create the string object using placement new and destroy it by calling the destructor explicitly. You might also want to make the data members of the union private to prevent the string from being accidentally assigned to (or otherwise accessed) while it's not constructed. I don't think anonymous unions can have constructors and destructors so you would probably have to use a named union instead.
If you know approximately how long the strings are going to be it might be easier to use a fixed size char array (C-string) instead of std::string.
But honestly, do you really need to use a union here? Why not make stock_id and stock_name members of stock_item?
union {
unsignedlonglong stock_id{0};
char stock_name[20];
};
at times, a stock item may not be allocated an ID, so a temporary name applies, but when an ID is allocated, then the string no longer applies, hence the union.
yes, category combined with a new attribute inWarehouse bool, which I didn't include in my first post. The struct in fact has many more attributes than what I originally posted.