I wrote two programs to understand the concept of copying objects. First one:
#include<bits/stdc++.h>
using namespace std;
class myInt
{
int x;
public:
myInt()
{
cout<< "default constructor is called" << endl;
}
myInt(int x)
{
cout<< "constructor is called with initializer" << endl;
this->x = x;
}
~myInt()
{
cout<< "destructor is called" << endl;
}
};
myInt func(myInt ob)
{
return ob;
}
int main()
{
myInt ob1(2);
func(ob1);
}
Output:
constructor is called with initializer
destructor is called
destructor is called
destructor is called
Here destructor was called 3 times which means 3 objects were created. One for object 'ob1', one for the 'ob' inside func() and another one while returning 'ob' from func(). My second code:
#include<bits/stdc++.h>
using namespace std;
class myInt
{
int x;
public:
myInt()
{
cout<< "default constructor is called" << endl;
}
myInt(int x)
{
cout<< "constructor is called with initializer" << endl;
this->x = x;
}
~myInt()
{
cout<< "destructor is called" << endl;
}
};
myInt func(myInt ob)
{
return ob;
}
int main()
{
myInt ob1(2);
myInt ob2 = func(ob1);
}
Output:
constructor is called with initializer
destructor is called
destructor is called
destructor is called
Here also 3 objects were created as the first one. But shouldn't there be one more destructor call for 'ob2' as I store the returning object from func() in it? Why the number of destructor call is same in both cases?