My code is
class CTemp{
public:
CTemp(){
printf("\nIn cons");
}
~CTemp(){
printf("\nIn dest");
}
};
void Dowork(CTemp obj)
{
printf("\nDo work");
}
int main()
{
CTemp * obj = new CTemp();
Dowork(*obj);
delete obj;
return 0;
}
The output that I get is
In cons
Do work
In dest
In dest
Now why does the constructor get called once but the destructor is called twice? Can someone please explain this?
Implement a copy constructor and check again:
When the function is called its parameter is created by using the implicit copy constructor. Add to your class the following copy constructor
to see one more message about creating an object
You've missed to count a copy-constructor and expected a constructor instead.
and
So, you have two objects and two destructor will be called.
Here local-copy will be done, that will be destruct after exit from scope of
DoWork
function, that's why you see destructor-call.