Reputation: 33
Suppose that there's a class called Vector, I want to overload the assignment operator for it to make it able to work like this: a = b = c;(a,b,v are objects of Vector class)
But one thing confused me. Suppose that there are two prototypes:
Vector & operator=(const Vector & v);
const Vector & operator=(const Vector & v);
Both two work in the case of 'a=b=c'. So, which one is better or right?
Upvotes: 1
Views: 49
Reputation: 610
Interesting, personally I would go with the first one, the reason for that is that the second one, is forcing constness on the result. Which might be something you don't want, also you can enforce constness externally if you want, by returning from outer functions with const etc. At least you might be able to manually modify vector components manually.
Upvotes: 1
Reputation: 118340
For starters, naming your class "Vector" will probably result in frequent confusion and mixups, with std::vector
. You should pick a better name. Unfortunately, "array" is also now taken...
The first one is the standard assignment operator. The assignment operator is only defined, of course, for mutable class instances, so it should return a reference to a mutable class instance.
Upvotes: 3