Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!watmath!watdragon!akwright From: akwright@watdragon.waterloo.edu (Andrew K. Wright) Newsgroups: comp.lang.c++ Subject: Re: unions and classes with constructors Keywords: union, constructor Message-ID: <11624@watdragon.waterloo.edu> Date: 17 Feb 89 16:26:51 GMT References: <11560@watdragon.waterloo.edu> <9595@ihlpb.ATT.COM> Reply-To: akwright@watdragon.waterloo.edu (Andrew K. Wright) Distribution: comp Organization: U. of Waterloo, Ontario Lines: 41 In article <9595@ihlpb.ATT.COM> nevin1@ihlpb.UUCP (55528-Liber,N.J.) writes: >In article <11560@watdragon.waterloo.edu> akwright@watdragon.waterloo.edu (Andrew K. Wright) writes: >>I would like to take issue with the rule that classes with constructors >>with constructors may not appear as elements of 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. > >But this blows my abstract notion of what a class is. To me, a class >is, among other things, an interface. A user of a class should not >have to worry about the details of the implementation of a class. >Calling a constructor explicitly requires me, from the user's point of >view, to understand something about how classes are implemented. You >should not have to go beneath the abstract level of "new" and "delete" >when using a class. [Note: by user, I don't include inheritance of >one class into another class.] The abstract notion of what a class is remains unchanged. It is the union construct, not the class notion, that is causing the problem here. When you use a C union, all bets are off. Because the union is untyped, you must be careful to use the union object correctly. The rule stating "classes with constructors cannot appear in a union" is an attempt to provide some measure of safety. But my point is that so long as one keeps the view that in using a union the programmer must be careful, this rule is overly restrictive. This is not really any different than unions in simple C. Although the rule appears to provide some protection for the class abstraction, there are plenty of other ways I can shoot holes in a class abstraction, so why bother to close this one so absolutely? The user of a union must be careful. If your union contains a class with a constructor, you must be careful to call the constructor when using that field (and destructor when done). If your union contains only simple types, int or float say, you must still be equally careful not to use a garbage value. I see no real difference. Andrew K. Wright akwright@watmath.waterloo.edu CS Dept., University of Waterloo, Ont., Canada.