0
#include <iostream>
using namespace std;

class A
{
   private :

     int m_n;
     static int copyconst;
     static int copydest;

   public :

     A()
     {
       cout<<"Default constructor"<<endl;
     }

     A(int n):m_n(n)
     {
        cout<<"Param constructor"<<endl;
        cout<<m_n<<endl;
     }

     A(const A&obj1)
     {
       ++copyconst;
       cout<<"Copy constructor"<<endl;
     }

     A& operator=(const A&obj)
     {
         cout<<"Assignment operator"<<endl;
     }

     ~A()
     {
       ++copydest;
     }

};

int A::copyconst = 0;
int A::copydest = 0;

int main()
{
    A a = 0;
    a = 2;
}

Output -

Param constructor
0
Param constructor
2
Assignment operator

I am not able to understand why I am getting this output can any one help?

Rishi
  • 1,387
  • 10
  • 14
Ayush Gupta
  • 77
  • 10
  • Add `explicit` keyword to constructor, to avoid such behavior. – AdvSphere Jan 24 '18 at 04:42
  • [This](https://stackoverflow.com/a/48414780) answer clearly explains the reason. If you want to avoid unnecessary creation, you can add an assignment operator with int. Example here: https://godbolt.org/g/rvDBZU You don't have to understand assembly. Just look for `call` and `jmp` instructions. – balki Jan 24 '18 at 05:21

2 Answers2

3

I am not able to understand why I am getting this output can any one help?

A a = 0;

is equivalent to:

A a(0);

That explains the first couple of lines of output.

a = 2;

is equivalent to:

a = A(2);

since there is no operator= function whose LHS is an A and the RHS is an int.

That explains the second couple of lines of output and the last line of output.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

I believe you understand the first two prints.

Param constructor
0

This is because A a = 0; is a call to the constructor and not the assignment operator (as the object is being constructed)

When you do

a = 2;

then 2 is first converted to an object of type A because A can take int argument and you have not declared the constructor explicit. Hence you see this output

Param constructor
2

Next, the assignment operator is called to assign the value of A(2) to a and hence this output

Assignment operator
Rishi
  • 1,387
  • 10
  • 14