Tuesday, January 08, 2013

[Cpp-Programming] Re: newbie q: difference between operator= and copy constructor?

Hi Harry!

Have a look at this tutorial here: http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/

The signatures are:
T(const T& o); // copy constructor
T& operator= (const T& o); // assignment operator

Most notable compiler behaviours are:
T a; // calls default constructor
a = someT; // calls assignment operator
T b(someT); // calls copy constructor
T c = someT; // calls copy constructor, too!

Note: the default behaviour for both copy ctor and assign operator is equal to a memcpy (shallow copy). When you overload one or both in your class, they can basically do whatever. Though it's usually a good idea to either completely emulate the copy & assignment behaviour of basic types (deep copy: no shared memory between objects) or use a different approach to accomplish anything more complex as your code gets very hard to debug when assigning and copying don't behave as expected.

Best,
BeyelerStudios

On Monday, 7 January 2013 20:42:10 UTC+1, Harry Potter wrote:
I think the answer to this may solve my previous post: What is the difference between an overloaded = operator and a copy constructor?  How do they behave in ISO C++?

--
You received this message because you are subscribed to the Google Groups "C++ Programming" group.
To view this discussion on the web visit https://groups.google.com/d/msg/cpp-programming/-/s8nnft-BIl4J.
To post to this group, send email to cpp-programming@googlegroups.com.
To unsubscribe from this group, send email to cpp-programming+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cpp-programming?hl=en.

0 Comments:

Post a Comment

<< Home