Friday, February 10, 2006
Understand Copy Constructor
compile in windows: cl /EHsc main.cpp
Output:
C:\c++Test>cat HowMany.out
after construction of h: object count = '1'
x argument inside f(): object count = '1'
~HowMany(): object count = '0'
after call to f(h): object count = '0'
~HowMany(): object count = '-1'
~HowMany(): object count = '-2'
Source Code
#include
#include
using namespace std;
ofstream out("HowMany.out");
class HowMany {
static int count;
public:
HowMany()
{
count++ ;
}
static void print(const string &msg="")
{
if (msg.size() != 0)
{
out << msg << ": " ;
}
out << "object count = '" << count << "'" << endl;
}
~HowMany()
{
count--;
print("~HowMany()");
}
};
int HowMany::count = 0;
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}
void main()
{
HowMany h;
HowMany::print("after construction of h");
HowMany h2 = f(h);
HowMany::print("after call to f(h)");
}