Reputation: 5451
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
Upvotes: 2
Views: 1615
Reputation: 1
for every object compiler should create copy constructor, here also copy constructor created for all object h, x and h2. But for h object copy constructor is no need. And next you are calling a function f with input argument as h. Here copy constructor invokes and it copies the content in h to x object. And for the next object h2 also same thing (here also copy constructor invokes and copies x to h2). Becuase of this reason only objectcount not incremented. thank you.
Upvotes: 0
Reputation: 126777
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:
HowMany(const HowMany &) {
objectCount++;
}
Upvotes: 9