Operator Overloading in C: आपने देखा है कि “C” में किस प्रकार से एक ही नाम के कई Functions को कई अलग-अलग कामों के लिये प्रयोग में लाया जा सकता है, जिसे Function Overloading कहा जाता है। Function.
I have used the following code for assignment operator overloading:
My Copy Constructor is this:
In the above operator overloading code, copy constructor is called as there is a new object is being created; hence I used the below code:
Its working perfectly and the copy constructor problem is avoided, but is there any unknown issues (to me) regarding this ?
kaushikkaushikThere are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.
Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.
juanchopanzajuanchopanzaUnder the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:
I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).
As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.
Jerry CoffinJerry CoffinThe second is pretty standard. You often prefer to return a reference from an assignment operator so that statements like a = b = c;
resolve as expected. I can't think of any cases where I would want to return a copy from assignment.
One thing to note is that if you aren't needing a deep copy it's sometimes considered best to use the implicit copy constructor and assignment operator generated by the compiler than roll your own. Really up to you though ...
Edit:
Here's some basic calls:
Now say we had the first version of your assignment operator:
It calls the copy constructor and passes a reference to this
in order to construct the copy to be returned. Now in the second example we avoid the copy by just returning a reference to this
it's right way to use operator overloadingnow you get your object by referenceavoiding value copying.