#include<iostream>
using namespace std;
class Test
{
private:
int x;
public:
Test(int i)
{
cout<<"Conversion constructor called..."<<endl;
x = i;
}
~Test()
{
cout<<"Destructor called..."<<endl;
}
void show()
{
cout<<" x = "<<x<<endl;
}
};
int main()
{
Test t(20);
t.show();
t = 30;
t.show();
return 0;
}
output:
Conversion constructor called...
x = 20
Conversion constructor called...
Destructor called...
x = 30
Destructor called...
When i am doing t = 30 why it is calling constructor and destructor? Please explain.Many thanks in advance.
There is no overload of =
that can be used to assign directly from an int
value. Your conversion constructor allows 30
to be converted to a Test
object, which can then be assigned using the implicitly-generated copy constructor (which copies each member). So your assignment is equivalent to
t = Test(30);
creating and destroying a temporary object to assign from.
You could avoid this by providing an assignment operator:
Test & operator=(int i) {x = i;}
in which case the assignment could use this directly, equivalent to
t.operator=(30);
When you write t = 30
, your compiler creates a temporary Test
variable, which it creates using the conversion constructor. After setting t
equal to this temporary variable, the temporary variable is then destroyed, calling the destructor.
Because t
is already defined, it cannot be initialized throug the convertion contructor.
Instead, it creates a temporay Test
object, calls the operator=, then delete it.
"why it is calling constructor and destructor?"
Because there's a (implicit) temporary instance of Test
constructed, assigned to t
and destructed after assignment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.