|
-
June 2nd, 2013, 11:33 AM
#7
Re: operator overloading and inheritance
 Originally Posted by tuli
I have added a proper example, sorry.
As 2kaud alluded to in post #5, for this new example, you fail to follow the rule of three, i.e., whenever you define the copy constructor, the copy assignment operator or the destructor, you should define all three. (Though sometimes you might define the destructor merely to declare it virtual, and other times you might disable copying instead.)
Additionally, unless you have special reasons for doing otherwise, the parameter of the copy assignment operator should be a const reference, not a non-const reference.
 Originally Posted by Paul McKenzie
I would highly suggest you not mix up assignment operators with copy construction. If anything, both functions can call a common function to do the internal copying, but you shouldn't call the assignment operator from the copy constructor. Doing so leads to confusing code, both to you and anyone trying to decipher what is attempting to be done.
First implement the copy constructor, assuming that there is no such thing as an assignment operator. Next, implement the assignment operator, assuming there is no thing as a copy constructor. Now take those two functions you implemented, factor out the common code, and place that common code into an internal "copy_elements" or similar function. Then change your assignment and copy functions to call this common function.
Not quite: before the advent of move constructors, it would be acceptable or even recommended to use the copy/swap idiom to implement the copy assignment operator. This would mean the usage of the copy constructor under the assumption that the copy constructor for A had been defined correctly. But yes, one should implement the copy constructor "assuming that there is no such thing as an assignment operator".
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|