Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!van-bc!ubc-cs!kiwi!egypt.mpr.ca!spencer From: spencer@egypt.mpr.ca ( Reid Spencer) Newsgroups: comp.lang.c++ Subject: Re: conversions Message-ID: <2141@kiwi.mpr.ca> Date: 13 Apr 90 00:57:50 GMT References: <7633@cadillac.CAD.MCC.COM> Sender: news@eric.mpr.ca Reply-To: spencer@egypt.mpr.ca ( Reid Spencer) Organization: Microtel Pacific Research Ltd. (MPR) Lines: 63 In article <7633@cadillac.CAD.MCC.COM>, vaughan@puma.cad.mcc.com (Paul Vaughan) writes: > > The following program compiles cleanly under g++-1.37.1, but gets > three errors under cfront (Sun CC, actually). > example omitted. > > Any comments on why CC generates these errors, and whether or not this > is the right thing to do? I realize that a class that works Exactly > like an int for both reading and assignment probably isn't very > useful, but should I be able to do it this way? > I'm not sure what you were intending with this example, but at first appearances it seems you simply forgot to override the "+=" operator for class "Int". I think, perhaps that you expected cfront to use the constructor to add the value of i to itself. However, even if that were semantically possible it wouldn't provide the results you want (i.i being 8, not 4). Why g++ accepts this program, I don't know. It's probably a bug in g++. cfront seems to be giving you the right messages. Here's the program with some modifications I made: ------------------------------------------ extern "C" { int printf(char *, ...); }; // new class Int { int i; public: Int(int j) : i(j) {} Int(Int& I) { i = I.i; } operator int() { return i; } operator int&() { return i; } Int & operator +=(Int &j) { i += j.i; return *this; } // new Int & operator +=(int j) { i += j; return *this; } // new }; main() { Int i = 4; i += i; // line 29 i += 1; // new printf("i.i is %d\n", int(i)); // new } ---------------------------------------------- The printf statement should print "i.i is 9". This kind of problem is a common misperception in C++. Please make note of the following statement: "the semantics of initialization and assignment are different". See Lippman's book "C++ Primer", pp. 243 and 268 for details. Also in Stroustrup, pp 178-180. Hope this helps ... _______________________________________________________________________________ Reid Spencer Software Engineer Voice: (604) 293-5334 MPR TelTech, Ltd. Fax: (604) 293-5787 8999 Nelson Way, Burnaby, BC Internet: spencer@egypt.mpr.ca Canada V5A 4B5 UUCP: uw-beaver!ubc-cs!eric!egypt!spencer