There's something I don't understand about how the assignment operator works, please have a look at this piece of code:
#include <iostream>
using namespace std;
class foo
{
int val{};
public:
foo()
{
}
foo( int n )
{
val = n;
cout<<"Constructor"<<endl;
}
foo( const foo& f )
{
cout<<"Copy constructor, val "<<endl;
val = f.val;
}
foo( const foo&& f )
{
cout<<"Copy constructor -rvalue-"<<endl;
val = f.val;
}
foo operator+( const foo& other ) const
{
cout<<"Sum "<<endl;
foo foo2;
foo2.val = val + other.val;
return foo2;
}
foo& operator=( const foo& f )
{
cout<<"Assignment operator\n";
val = f.val;
return *this;
}
foo& operator=( const foo&& f)
{
cout<<"Assignment operator, r-value\n";
val = f.val;
return *this;
}
~foo() {}
};
int main()
{
foo a{1}, b{5}, c{4};
foo d;
d = a + b + c;
foo d2 = a + b + c;
return 0;
}
The output of this application is:
Constructor
Constructor
Constructor
Sum
Sum
Assignment operator, r-value
Sum
Sum
What is not clear to me is why the second assignment trigger no assignment operator. The first assignment is on an object which was constructed via the default construction and then a plain assignment operation is visible, in the second one a temporary object should be builded by the compiler and then assigned to d2, but no print are visible from any of the assignment operators provided. Why?
Thanks