Newsgroups: comp.lang.c++ Path: utzoo!utgpu!cunews!csi.uottawa.ca!news From: hitz@sim5.csi.uottawa.ca (Martin Hitz) Subject: Re: Constructor question Message-ID: <1991Apr12.150506.4069@csi.uottawa.ca> Summary: Is expensive Sender: news@csi.uottawa.ca Nntp-Posting-Host: sim5 Organization: University of Ottawa References: <1991Apr2.110623.22219@and.cs.liv.ac.uk> <20164@alice.att.com> <17400@sunquest.UUCP> Date: Fri, 12 Apr 91 15:05:06 GMT In article <17400@sunquest.UUCP> francis@sunquest.UUCP (Francis Sullivan) writes: >>> Can I call one constructor to class X explicitly from within another >>> constructor to class X ? > >Yes, by using operator= > >#include > >class X { > int j; > >public: > X(int i) : j(i) { printf("Called X(int=%d): j=%d\n", i, j); } //1 > X(char *cp, int i) { > *this = X(i); > printf("Called X(char *cp= '%s', int=%d): j=%d\n", cp, i, j); //2 > } >}; > >main() { > X x("test", 5); >} Although this works in principle, one should be aware of the fact that X(i) on the right hand side of the assignment usually generates a temporary anonymous instance of X which is copied to the lhs and then destroyed. So this might be an expensive way of doing initialization. However, some compilers might optimize it. Exchanging the lines //1 and //2 by X(int i) : j(i) { printf("Called X(int=%d): j=%d this=%ld\n", i, j, this); }//1 printf("Called X(char *cp= '%s', int=%d): j=%d this=%ld\n", cp, i, j, this);//2 yields Called X(int=5): j=5 this=84813140 Called X(char *cp= 'test', int=5): j=5 this=84813136 using Zortech (2 distinct objects are involved) but results in Called X(int=5): j=5 this=-134218552 Called X(char *cp= 'test', int=5): j=5 this=-134218552 using g++ (only 1 object). Martin Hitz (hitz@csi.UOttawa.CA)