Search code examples
c++operator-overloadingassignment-operator

Example applications of overloading the assignment operator


I hope this isn't seen "primarily opinion based" or "too broad". It's fairly straight forward question:

What are some example problems to which overloading the assignment operator offers a solution?

I don't think I've yet seen a situation in which it would be useful, especially considering the negative implications of having a program full of surprise implicit behaviours and "smoke and mirrors".


Solution

  • Example:

    struct X
    {
        int *p;
        X(): p{new int[42]}
        ~X() { delete p; }
    };
    

    What will happen if you do

    X x, y;
    x = y;
    

    ? The default assignment operator will copy the raw pointer, and you'll end up delete-ing the same pointer twice by the destructors of x and y. In fact, you'd better declare a copy constructor here too (or, even better, use smart pointers). Note that in

    X x = some_obj;
    

    the copy constructor is invoked (or elided if the rhs is a prvalue). The assignment operator is invoked only after construction, when you say

    x = some_other_obj; // x is already constructed here
    

    If you ask whether the operator= should exist at all (in contrast to e.g. Java), then it's probably a matter of personal preference.