For example in the code below :
class HowMany {
static int objectCount;
public:
HowMany() {
objectCount++;
}
static void print(const string& msg = "") {
if(msg.size() != 0)
cout << msg << ": ";
cout << "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()");
}
Why does the compiler doesn’t create the copy-constructor automatically for the class HowMany, and bit-wise copy takes place when the call to f(h) takes place ?
In what cases the compiler creates the default copy-constructor and in what cases it doesn’t create?
It gives output as:
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
Many many thanks in advance
In C++98 and C++03 the compiler always creates a copy constructor, that performs a memberwise copy of your fields, unless you specify explicitly that you wrote your own1.
This is what happens in your code: the compiler-generated copy constructor doesn’t do anything particular – in particular, it doesn’t increment
objectCount– so you end up with a negative object count (all the copied objects didn’t increment the counter, but they did decrement it).To obtain the result you expected, you would have to write something like: