The Assignment operator=

Started by
2 comments, last by Anon Mike 18 years ago
Consider: class Test { public: Test& operator=( const Test& t ) { cout << "Assignment\n"; m_Val = t.m_Val; return( *this ); } int m_Val; }; void func( Test t ) { cout << "func: " << t.m_Val << "\n"; } void main() { Test T1; T1.m_Val = 5; Test T2 = T1; //assignment operator is not called here but members are copied func( T1 ); //assignment operator not called, members are copied T2 = T1; //assignment operator called } Why is it for the case of Test T2 = T1 the assignment operator does not get called? How do we fix this?
Advertisement
In your case the Copy Constructor is called.
Well done!

Interestingly, if you have a function that returns an object and assign it to something else, the copy constructor is called followed by the assignment operator.

Test func()
{
Test t;
return( t );
}

Test t = func(); //only copy constructor
t = func(); //copy constructor then assignment

[Edited by - Simplicity on April 17, 2006 3:42:43 PM]
To expand a bit, although "Text t = func();" sure looks like it's using the assignment operator it really isn't. It's really just syntax-suger for "Text t(func());".
-Mike

This topic is closed to new replies.

Advertisement