Sign in to follow this  
Simplicity

The Assignment operator=

Recommended Posts

Simplicity    158
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
Simplicity    158
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
Anon Mike    1098
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

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