Search code examples
c++constructorassignment-operator

Why is parameterized constructor called, when we assign an integer value to an object of a class?


The code is:

#include<iostream>
using namespace std;

class Integer
{
    int num;

    public:
        Integer()
        {
            num = 0;
            cout<<"1";
        }
        
        Integer(int arg)
        {
            cout<<"2";
            num = arg;
        }
        int getValue()
        {
            cout<<"3";
            return num;
        }

};

int main()
{
    Integer i;
    i = 10;  // calls parameterized constructor why??
    cout<<i.getValue();
    return 0;

}

In the above code, the statement i=10 calls the parameterized constructor. Can you please explain this.


Solution

  • Your parameterized constructor is a converting constructor. C++ is all too happy to make an expression valid, so long as it can find a reasonable conversion sequence to make things work. So as already noted, 10 is converted to an Integer temporary, which then gets assigned by the compiler generated operator= (Integer const&).

    If you wish to prevent the constructor from being used in unexpected conversions, you can mark it as explicit.

    explicit Integer(int arg) { /* ... */}
    

    It then stops being a converting constructor, and the assignment will not be possible without a cast (or custom assignment operator, provided by you).