Search code examples
c++constructoroperator-overloadingassignment-operator

Overloading the assignment operator vs. providing an implicit constructor


I have just learned on page 563 of C++ Primer (5th edition) that one can overload the assignment operator. So, if I am writing a class C and it makes sense to assign an integer to an object of this class, then I can provide an assignment operator with an rhs of type int. Then the clients of my class can write:

C c;
...
c = 5;

Question: Is it true that if such an assignment makes sense, then an implicit constructor C(int); should also make sense? If so, then I should really define this constructor instead (which has other uses as well) and never need to overload the assignment operator. Am I missing something?


Solution

  • If C defines a non-explicit constructor taking an int then you don't necessarily need an assignment operator taking an int, but it may end up being more efficient.

    If operator=(int) exists:

    C c; //default constructor
    c = 5; //assignment from int
    

    If C(int) exists and operator=(int) does not:

    C c; //default constructor
    c = 5; //construction of temporary from int, then assignment from C
    

    If move semantics are efficient for C then the latter may be acceptable. If not, you might want to define that operator=(int) anyway. Ultimately, this depends on a number of factors, like how often you are going to be assigning to C, how expensive copies are etc. Understand the issues, work out how they apply to your class, then choose the most reasonable solution.