Path: utzoo!utgpu!water!watmath!clyde!att-cb!att-ih!pacbell!ames!mailrus!umix!uunet!mcvax!unido!gmdka!fuchs From: fuchs@gmdka.UUCP (Harald Fuchs) Newsgroups: comp.lang.c++ Subject: Re: Following code bombs (possible assignment/initialization problem)? Message-ID: <273@gmdka.UUCP> Date: 8 Mar 88 12:18:41 GMT References: <400@erc3ba.UUCP> Organization: GMD Karlsruhe, W-Germany Lines: 38 Posted: Tue Mar 8 13:18:41 1988 in article <400@erc3ba.UUCP>, rsc@erc3ba.UUCP (Rich Chomiczewski, AT&T - ERC, Princeton NJ) says: > The following program blows the stack: > ... > class Position { > Point off; // offset is relative to (possibly null) ``to''. > Position *to; > public: > Position(Point p) { off = p; to = 0; } > Position(Point p, Position pos) { off = p; to = &pos; } > Point position() { return (to) ? off+to->position() : off; } > }; > main() > { > Position a = Position(Point(1,1)); > Position b = Position(Point(5,5), a); > Position c = Position(Point(10,10), b); > } The bug in this program is Position(Point p, Position pos) { off = p; to = &pos; } where you take the address of an object on the stack because pos is passed by value. Use reference passing (Position& pos) and the problem disappears. When you declare Position a = Position(Point(1,1)); the following functions are called: Position::Position (Point); // To make a temporary Position value Position::Position (Position&); // Initialisation of a by temp // See The Book p. 180 Position::~Position (); // To get rid of temp Since you didn't declare Position::Position (Position&), Cfront picks the default, namely bitwise copy. That happens to be ok in this context. Harald Fuchs UUCP: ...!uunet!mcvax!unido!gmdka!fuchs X.400: fuchs@karlsruhe.gmd.dbp.de