Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uunet!brunix!sdm From: sdm@cs.brown.edu (Scott Meyers) Newsgroups: comp.lang.c++ Subject: Re: constructors and initializers Keywords: constructor, default, class, array, definition Message-ID: <75068@brunix.UUCP> Date: 9 May 91 15:33:14 GMT References: <1991May2.165955.28385@iitmax.iit.edu> <701@taumet.com> <1991May8.155352.18313@alias.com> Sender: news@brunix.UUCP Reply-To: sdm@cs.brown.edu (Scott Meyers) Organization: Brown University Department of Computer Science Lines: 45 In article <1991May8.155352.18313@alias.com> rae@alias.com (Reid Ellis) writes: | A note about initializers in constructors. Recently, the following | class was mentioned under the subject line "HELP: default constructor | for array of class": | | class Point { | int x; | public: | Point() { x = 200; } | Point(int xc = 100) { x = xc; } | }; | | Not to belabor the point [pun intentional] but the constructors should | be written as: | | class Point { | int x; | public: | Point() : x(200) {} | Point(int xc = 100) : x(xc) {} | }; | | i.e. use initializers rather than assignment in a constructor. Why? | The following line of code won't work with the first version, but will | work with the second version: | | const Point kPoint(23); But it will work. It's perfectly acceptable to invoke constructors (and destructors) on const objects -- see the ARM section 9.3.1, p. 178. Although the ARM doesn't explicitly say it anywhere, it seems to be the case that a const object doesn't become const until after construction is complete (including the body of the constructor), and it ceases to be const once destruction commences. This seems to me to be the only practical semantics, since you can't always do everything you want to through the member initialization list. For the more empirical in the audience, the above code also compiles and runs under cfront 2.0, 2.1, and g++ 1.39. Scott ------------------------------------------------------------------------------- What do you say to a convicted felon in Providence? "Hello, Mr. Mayor."