Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!elroy.jpl.nasa.gov!decwrl!world!wmm From: wmm@world.std.com (William M Miller) Newsgroups: comp.lang.c++ Subject: Re: Incorrect handling of destructors in Turbo C++ Keywords: Turbo C++, destructors Message-ID: <1991Mar25.034657.20995@world.std.com> Date: 25 Mar 91 03:46:57 GMT References: <546@humu.NOSC.Mil> Organization: The World Public Access UNIX, Brookline, MA Lines: 36 kent@humu.nosc.mil (Kent K. Kuriyama) writes: > void main() > { > A a; > > printf("before call\n"); > sub(a); > printf("after call\n"); > } > ------------ > > When this program is executed: > > ------------ > Constructor called > before call > in sub > after call > Destructor called > Destructor called > ------------ > > Am I wrong to think that the destructor should only be called once? Yes. C++ has, by default, the call-by-value semantics of C. When you called "sub(a)", an object was created to hold the copy of "a" that was actually passed to "sub()." Since you didn't provide a constructor that could be used for this purpose (it's called a "copy constructor" and is declared as "A::A(const A&)"), the compiler generated a default one for you that just did a bit-for-bit copy. Naturally, the default one didn't have a printf() call in it, so its execution didn't show up in your output. Of the two destructors, one is for the copy passed to "sub()," the other is for "a." -- William M. Miller, Glockenspiel, Ltd. wmm@world.std.com