2
#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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
paddy
  • 15
  • 4

4 Answers4

3

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);
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

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.

wolfPack88
  • 4,163
  • 4
  • 32
  • 47
1

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.

LeeNeverGup
  • 1,096
  • 8
  • 23
1

"why it is calling constructor and destructor?"

Because there's a (implicit) temporary instance of Test constructed, assigned to t and destructed after assignment.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190