• Advertisement
Sign in to follow this  

The Assignment operator=

This topic is 4332 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
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]

Share this post


Link to post
Share on other sites
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());".

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement