I have question on the below code. In the main function what will happen when the line: obj = 20; is executed. I am not able to understand why it calls the constructor? Could anyone of you please explain?
#include <iostream>
#include <string>
using namespace std;
class Int {
int x;
public:
Int(int x_in = 0)
: x{ x_in }
{
cout << "Conversion Ctor called" << endl;
}
operator string()
{
cout << "Conversion Operator" << endl;
return to_string(x);
}
};
int main()
{
Int obj(3);
string str = obj;
obj = 20;
string str2 = static_cast<string>(obj);
obj = static_cast<Int>(30);
return 0;
}
CodePudding user response:
Within the class there is not defined the assignment operator operator =( int )
. But the class has the conversion constructor
Int(int x_in = 0)
So in this statement
obj = 20;
there is called the constructor like Int( 20 )
to convert the integer value to an object of the type Int
that can be assigned to the object obj
due to the implicit move assignment operator generated by the compiler.
CodePudding user response:
Lacking a assignment operator taking int
, your compiler uses the next best assignment operator it can get it's hands on, which is the implicitly declared move assignment operator (Int::operator=(Int&&)
). To use this operator, a rvalue reference to a Int
object is required, which the compiler creates using the constructor Int::Int(int)
, i.e. the compiler treats obj = 20;
as
obj.operator=(Int(20));
To see what's happening here, you could implement the move assignment operator yourself to print something to the console when the assignment operator is executed:
class Int
{
...
public:
...
Int& operator=(Int&& other)
{
std::cout << "move assignment of Int, new value: " << other.x << '\n';
x = other.x;
return *this;
}
// the following members are only declared to make sure the available
// constructors/operators are the same as in the original version of the code
Int(Int&&) = default;
Int& operator=(Int const&) = default;
Int(Int const&) = default;
};