P
Piggy
using namespace std;
class foobar {
public:
foobar() { cout << "foobar::foobar()\n"; }
~foobar() { cout << "foobar::~foobar()\n"; }
foobar(int nval ):_ival(nval) { cout << "foobar::foobar(int)\n"; }
foobar( const foobar &rhs ) { cout << "foobar::foobar( const foobar
& )\n"; }
operator int(){ cout<<"foobar:perator int()"<<endl; return _ival; }
private:
int _ival;
};
foobar f( int val )
{
return foobar();
}
void main()
{
foobar foo = f(1024);
}
In the above program,
I see 3 different behaviors:
1. Run the program as it is, only one foobar object is created.
2. Remove the const qualifier from the copy constructor, there are 3 foobar
objects created. Strange thing is that "operator int()" method is used while
copying data to temporary objects. Why?
3. commenting the "operator int()" method will result back in only one
foobar object creation.
Could anyone kindly explain the behavior for me?
class foobar {
public:
foobar() { cout << "foobar::foobar()\n"; }
~foobar() { cout << "foobar::~foobar()\n"; }
foobar(int nval ):_ival(nval) { cout << "foobar::foobar(int)\n"; }
foobar( const foobar &rhs ) { cout << "foobar::foobar( const foobar
& )\n"; }
operator int(){ cout<<"foobar:perator int()"<<endl; return _ival; }
private:
int _ival;
};
foobar f( int val )
{
return foobar();
}
void main()
{
foobar foo = f(1024);
}
In the above program,
I see 3 different behaviors:
1. Run the program as it is, only one foobar object is created.
2. Remove the const qualifier from the copy constructor, there are 3 foobar
objects created. Strange thing is that "operator int()" method is used while
copying data to temporary objects. Why?
3. commenting the "operator int()" method will result back in only one
foobar object creation.
Could anyone kindly explain the behavior for me?