Copy Constructor

Hi All, I am going through a book for CPP. While explaining the utility of the copy constructor, following program is given.

#include <fstream>
#include <string>
using namespace std;
ofstream out("HowMany.out");

class HowMany {
static int objectCount;
public:
HowMany() { objectCount++; }
static void print(const string& msg = "") {
if(msg.size() != 0) out << msg << ": ";
out << "objectCount = "
<< objectCount << endl;
}
~HowMany() {
objectCount--;
print("~HowMany()");
}
};

int HowMany::objectCount = 0;

// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}

int main() {
HowMany h;
HowMany::print("after construction of h");
HowMany h2 = f(h);
HowMany::print("after call to f()");
}

The output of the above program is as follows:
after construction of h: objectCount = 1
x argument inside f(): objectCount = 1
~HowMany(): objectCount = 0
after call to f(): objectCount = 0
~HowMany(): objectCount = -1
~HowMany(): objectCount = -2

The author gave some explanation. But i am still confused why there are 3 destructors called. Can anyone explain me the logic?

Thanks in Advance,
Rahul
You aren't increasing 'objectCount' in the copy constructor -you are using the copy constructor given by the compiler-,
so not all the objects of 'HowMany' will increase that when constructed but all of them will decrease it with the destructor.
For this reason you get negative values.

-Please use [code][/code] tags when postig code-
Topic archived. No new replies allowed.