Object creation process while copying
Dec 26, 2009 at 11:04pm UTC
Hello
I realized something that I couldn't figure out. Let's say I have a class
X and a function,
func , which returns a
list<X> . When I get the result of
func , the copy operator should work I think, but it seems not.here's my code and output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include<iostream>
#include<list>
using namespace std;
class X
{
public :
X()
{
cout<<"Default Constructor called\n" ;
}
X(string data):
_data(data)
{
cout<<"Constructor called\n" ;
}
X(const X& x)
{
_data = x._data;
}
void operator =(const X& x)
{
cout<<"Copy operator called\n" ;
_data = x._data;
}
~X()
{
cout<<"Destructor called\n" ;
}
string _data;
protected :
private :
};
list<X> func()
{
list<X> lst;
X x1("obj name" );
lst.push_back(x1);
return lst;
}
int main()
{
list<X> lst = func();
X x1 = lst.back();
cout<<x1._data<<"\n" ;
}
output:
--------------
Constructor called
Destructor called
obj name
Destructor called
Destructor called
Why didn't the copy operator and the default constructor called?
What does it do when it executes this line?:
list<X> lst = func();
Thanks in advance.
Dec 26, 2009 at 11:06pm UTC
That line calls the copy constructor ( which is at line 17 in your code )
Dec 26, 2009 at 11:21pm UTC
Thanks for the quck reply. I got it.
Also I realized that;
X x1 = lst.back();
calls copy constructor, but
1 2
X x1;
x1 = lst.back();
calls at first default constructor and then the copy operator.
Thanks again for the reply.
Topic archived. No new replies allowed.