Sign in to follow this  

The Assignment operator=

This topic is 4256 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
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

This topic is 4256 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this