1

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?

1
  • CopyAssignable as a requirement in the standard is defined in terms of the first, so you should probably go with that. Commented Feb 19, 2016 at 12:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I see. But the order of assignment is right to left, so I think there's no influence or bug when use this class, right? what do you think.
1

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.

3 Comments

Thanks, I see. But the order of assignment is right to left, so I think there's no influence or bug when use this class, right? what do you think.
order of operation is not right to left, it depends on the operation involved, i am not sure there is guarantee about that, i think is implementation specific. But not 100% sure I will look for more info on that. I am not sure what you mean by influence or bug. Please elaborate
I found that the second is bad, for example: (a=b)=c won't work(maybe no one write like this). I decide to go with the first one, thanks anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.