0

I have found lots of examples online for how to overload other operators like +, - and ==, but nothing for =. First, I tried

CharArrayList operator=(const CharArrayList &list);

The compiler complained, saying I had one parameter instead of two.

Next, I tried

CharArrayList operator=(const CharArrayList &before, CharArrayList &after);

The compiler complained again, saying I had three parameters instead of two.

How can I make my overloaded = operator contain exactly two parameters?

K Man
  • 602
  • 2
  • 9
  • 21
  • There's no way to overload a global assignment operator for a type. Use explicit constructor or member assignment operator overloads. – πάντα ῥεῖ Jun 04 '22 at 16:11
  • `operator=` should be a member of `CharArrayList`. See info and examples here: https://en.cppreference.com/w/cpp/language/copy_assignment. – wohlstad Jun 04 '22 at 16:13
  • `CharArrayList operator=(const CharArrayList &list);` is correct when used inside a class definition. `=` cannot be overloaded outside of a class. – user17732522 Jun 04 '22 at 16:13
  • Typically it also returns by reference, not by value. – Nathan Pierson Jun 04 '22 at 16:20
  • 1
    Side note: [What is the copy-and-swap idiom?](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) describes a ridiculously simple, nearly fool-proof way to make an assignment operator. It's not always the most efficient solution, but it makes a great starting point and profiling will let you know if you need to do something else. – user4581301 Jun 04 '22 at 16:32
  • 1
    @user4581301 Although writing your class in such a way that the compiler-generated default assignment operator works is often even more foolproof – Nathan Pierson Jun 04 '22 at 16:43
  • That's truth. Always apply the Rules of Three and Five as close to the guarded resource as possible so that everything above it can be written to observe the Rule of Zero. – user4581301 Jun 04 '22 at 16:46

0 Answers0