TITLE: anonymous unions (Newsgroups: comp.lang.c++.moderated, 31 July 99) DEROCCO: Paul D. DeRocco >I read the standard the same way, but with respect to _anonymous_ >unions, I can't see any use for them, except to be able to stuff >something in via one name, and pull it out again via another name. Can >you? KOENIG: Andrew Koenig Sure. Typical use is in conjunction with another variable that tells the program which component is in use. For example: class Number { // ... private: union { int i; NumberRep* p; }; bool is_int; // ... }; This example might be part of a class that can represent any of several kinds of numbers. To avoid an indirection in the common case, we store an integer right in the object; any other kind of number is stored in dynamically allocated memory. Another possibility: class String { // ... private: unsigned size; union { char s[8]; char* p; }; // ... }; Here, we store the string right in the object if it contains 8 characters or fewer; otherwise we store them in dynamically allocated memory. We use the size to decide which union component is active.