Wednesday, January 09, 2013

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

If I want to pass a class defined using new in one function as a reference to another function, the class becomes corrupt.  Maybe the wrong address is passed.  Or maybe the class is out-of-scope.  When I pass a class as a reference to a function, is there anything I need to know?  I've been able to narrow the bug with my program down to a function call: before the.call, everything work fine,  Within the called function, the class becomes unreadable and member function calls return garbage.

On Tuesday, January 8, 2013 9:08:48 AM UTC-5, Harry Potter wrote:
Thank you for your help.  I'll look at the site later.  BTW, it seems that, when I pass a class with a char* (I used the new declarator to define a class) and a function to return a modified version of the char* to another function, the member function returns corrupt information for the char*.

On Tuesday, January 8, 2013 3:58:02 AM UTC-5, Beyeler Studios wrote:
Hi Harry!


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/-/dPWjl2JpSocJ.
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