I have the following c++ code.
My problem here is that copy constructor also gets invoked when i try to call the assignment operator...
In the below source code in the main funtion in line no 36 i have tried to assign the assignment operator... but if u observe the output then, first the copy constructor is called and then the assignment operator is invoked after the copy constructor...
could any one thus let me know where i made the mistake...
As Grey Wolf points out, the paremeter to the assignment operator should be const reference. The same applies to the copy constructor. In addition, the return value from the assignment operator should be a reference to the object itself. I also recommend declaring the constructor that takes an int explicit. The declarations becomes:
1 2 3 4
9. alpha()
10. explicit alpha(int d)
15. alpha(const alpha& a)
22. alpha& operator=(const alpha& a)
Your assignment operator should make the assigned object equal to the right hand object. It should set data to o.data. If that is not the behavior you want, you do not want an assignment operator at all. It's not good practice to create an assignment operator that does something different. If the only thing you do in the assignment is to set data = o.data, you don't need to check if the object is assigned to itself. However it's good practice to always do it.
I don't think any of this actually helps you with your question.
The answer is very simple:
alpha a3(a2);
The line above should call the copy constructor. The same is true for this:
alpha a3 = a2;
If you want to use the assignment operator you have to do this:
1 2
alpha a3;
a3 = a2;
However, this should not matter to you, because if you design these operations propertly, the results should be equivalent.
hi everyone,
Thanks for the help,
but even after changing the parameter to the following operator function the copy constructor is being evoked.
ropez,
the line 36 should call the assignment operator only after the following modification to the code... but the thing is that first assignment operator is being called and secondly the copy constructor is invoked when it is called in the following way
and this code //data= a.data/2; was used in my first post just to check whether the copy construction was being called or the assignment operator was called.
Ok. I see now. I thought you ment line 42, because you had a comment there. In line 36, the assignment operator is called, as you expected. But you also got a call to the copy constructor which you didn't expect.
In this case, the answer is really to make both the parameter AND the return value from the assignment operator a reference (&).
Declare the four functions as in my first post, and you shouldn't have a problem.