Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!att!ucbvax!ulysses!ulysses.att.com!mwb From: mwb@ulysses.att.com (Michael W. Balk) Newsgroups: comp.lang.c++ Subject: Re: constructors and initializers Summary: Assignment in constructor OK! Keywords: constructor, default, class, array, definition Message-ID: <14758@ulysses.att.com> Date: 11 May 91 22:42:31 GMT References: <1991May2.165955.28385@iitmax.iit.edu> <701@taumet.com> <1991May8.155352.18313@alias.com> Sender: netnews@ulysses.att.com Lines: 38 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); Using Cfront 2.1 and the first definition of class Point above (the one with assignment in the constructors), I have no trouble compiling a main that creates const Point kPoint(23). And, Point::x actually gets the value 23 in the definition of kPoint when I add a print member function to examine it. Mike Balk AT&T Bell Laboratories Murray Hill, NJ 07974 mwb@ulysses.att.com