Path: utzoo!utgpu!watmath!watdragon!akwright From: akwright@watdragon.waterloo.edu (Andrew K. Wright) Newsgroups: comp.lang.c++ Subject: unions and classes with constructors Keywords: union, constructor Message-ID: <11560@watdragon.waterloo.edu> Date: 15 Feb 89 02:16:36 GMT Distribution: comp Organization: U of Waterloo, Ontario Lines: 39 Though this may appear at first to be yet another posting about constructors, I believe this issue is new, or at least has not appeared for some time. I would like to take issue with the rule that classes with constructors with constructors may not appear as elements of a union. This rule is mentioned in Bjarne's book, and is enforced by cfront 1.2 The rule seems to me to be overly restrictive. It is clear why it is needed: since unions have no tag, the compiler cannot possibly determine, even at runtime, which element of the union a constructor/destructor should be called. BUT, there are cases when it is not important. If no destructor is defined for a class, and if the constructor for a class does not take over storage allocation for the class, then it seems reasonable to allow the user to place such a class in a union. So long as the user calls the constructor explicitly for the field (s)he wishes to use, no problem occurs. This is analogous to remembering to intialize locals before you use them. You must initialize a union field before you use it. An example of where this is desirable is in using YACC with C++. Currently you are prevented from using a class with a constructor in YACC's %union construction, because YACC's %union is implemented with a C(++) union. In fact, YACC type checks all uses of $ variables, so YACC's %union is type safe. Thus the restriction that C++ imposes seems unnecessary here, IF your class has no destructor and does not take over storage allocation. eg. class Complex { double re, im; Complex( double r, double i ) { re = r; im = i; } } With the above simple class, there seems no reason not to allow it inside a union. Any chance this might be addressed in upcoming releases of C++? How do other people deal with the YACC issue mentioned above? (I have several potential solutions, none of which I like). Andrew K. Wright akwright@watmath.waterloo.edu CS Dept., University of Waterloo, Ont., Canada.