U
utab
Dear all, I have got a simple example to demonstrate the need for copy
construction but one point is not clear to me. When returning from the
function in main h2 is not constructed why? I marked that point and
that is also obvious from the output
#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:bjectCount = 0;
// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}
int main() {
HowMany h;
HowMany:rint("after construction of h");
HowMany h2 = f(h);
//////////////////////////////////////////// THIS POINT
HowMany:rint("after call to f()");
} ///:~
The output:
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 Thanks.
construction but one point is not clear to me. When returning from the
function in main h2 is not constructed why? I marked that point and
that is also obvious from the output
#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:bjectCount = 0;
// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}
int main() {
HowMany h;
HowMany:rint("after construction of h");
HowMany h2 = f(h);
//////////////////////////////////////////// THIS POINT
HowMany:rint("after call to f()");
} ///:~
The output:
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 Thanks.