9.14 — Overloading the assignment operator

The assignment operator (operator=) is used to copy values from one object to another already existing object.

Assignment vs Copy constructor

The purpose of the copy constructor and the assignment operator are almost equivalent -- both copy one object to another. However, the copy constructor initializes new objects, whereas the assignment operator replaces the contents of existing objects.

The difference between the copy constructor and the assignment operator causes a lot of confusion for new programmers, but it’s really not all that difficult. Summarizing:

  • If a new object has to be created before the copying can occur, the copy constructor is used (note: this includes passing or returning objects by value).
  • If a new object does not have to be created before the copying can occur, the assignment operator is used.

Overloading the assignment operator

Overloading the assignment operator (operator=) is fairly straightforward, with one specific caveat that we’ll get to. The assignment operator must be overloaded as a member function.

This prints:


This should all be pretty straightforward by now. Our overloaded operator= returns *this, so that we can chain multiple assignments together:

Issues due to self-assignment

Here’s where things start to get a little more interesting. C++ allows self-assignment:

This will call f1.operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves. In this particular example, the self-assignment causes each member to be assigned to itself, which has no overall impact, other than wasting time. In most cases, a self-assignment doesn’t need to do anything at all!

However, in cases where an assignment operator needs to dynamically assign memory, self-assignment can actually be dangerous:

First, run the program as it is. You’ll see that the program prints “Alex” as it should.

Now run the following program:

You’ll probably get garbage output. What happened?

Consider what happens in the overloaded operator= when the implicit object AND the passed in parameter (str) are both variable alex. In this case, m_data is the same as str._m_data. The first thing that happens is that the function checks to see if the implicit object already has a string. If so, it needs to delete it, so we don’t end up with a memory leak. In this case, m_data is allocated, so the function deletes m_data. But str.m_data is pointing to the same address! This means that str.m_data is now a dangling pointer.

Later on, we allocate new memory to m_data (and str.m_data). So when we subsequently copy the data from str.m_data into m_data, we’re copying garbage, because str.m_data was never initialized.

Detecting and handling self-assignment

Fortunately, we can detect when self-assignment occurs. Here’s a better implementation of our overloaded operator= for the Fraction class:

By checking if our implicit object is the same as the one being passed in as a parameter, we can have our assignment operator just return immediately without doing any other work.

Note that there is no need to check for self-assignment in a copy-constructor. This is because the copy constructor is only called when new objects are being constructed, and there is no way to assign a newly created object to itself in a way that calls to copy constructor.

Default assignment operator

Unlike other operators, the compiler will provide a default public assignment operator for your class if you do not provide one. This assignment operator does memberwise assignment (which is essentially the same as the memberwise initialization that default copy constructors do).

Just like other constructors and operators, you can prevent assignments from being made by making your assignment operator private or using the delete keyword:

9.15 -- Shallow vs. deep copying
9.13 -- Converting constructors, explicit, and delete

62 comments to 9.14 — Overloading the assignment operator

  • Aniket

    As assign operator share the same memory for assign object.
    suppose if we have two objects and A1 and A2;
    A1 = A2;
    Now change in A2 data can it reflect in A1 data or vice versa?

    • Alex

      It shouldn't. Assignment should only copy values, not link the two objects together in some way. I discuss this further in the next lesson, on shallow vs deep copying.

  • Silviu

    When we use operator= ,C++ always generates a copy constructor, just to work ? I mean operator= works with a copy constructor ?

  • TC

    Hi Alex,

    Thanks for replying to my other questions. For some reason, my browser has no reply button so that I can say thank you to you regarding your prompt and wise response.

    For this lesson, I have the following question.

    By checking if our implicit object is the same as the one being passed in as a parameter, we can have our assignment operator just return immediately without doing any other work.

    Since the == operator is not overloaded, we are just checking that whether the fraction's address is equal to this object's address. Am I correct?

  • Fortunato Rosa

    Hello Alex, first of all I want to compliment with you about this C++ course which is fantastic and very clear. I have a question about the "=" operator overload:
    take this snapshot of code

    How can resolve this problem?
    I need to instantiate dynamically an array of custom class object (and I saw that keyword new is also instantiating that dynamic object with the default constructor) with a custom costructor parameter for each object.


    • nascardriver

      Hi Fortunato!

      Your compiler tried to generate a default Hello::operator= looking like so

      Since your compiler failed to generate the operator= it marked it as a deleted function, so you can't use it.
      You need to either manually define the operator= in @Hello or make @value non-const to allow the default operator= to function.

      • Fortunato Rosa

        Hello Nascardriver, thank you for your reply!
        Even redefining "=" operator (or defining because the default one is automatically discarded for the reasons you said),I can't assign a value to a static value.
        In my project, I changed every const member in a non-const just because I want
        that this assignment would be possibile. But doing that it's like I'm changing the behaviour of member's class.

        • nascardriver

          > I can't assign a value to a static value.
          You mean const? That's what const is for, it disallows modifications of a variable.

  • Nimbok

    In the self-assignment example, you state, "Later on, when we’re copying the data from str into our implicit object, we’re accessing dangling pointer str.m_data. That leaves us either copying garbage data or trying to access memory that our application no longer owns (crash)."

    str.m_data IS m_data, which you've just reallocated, so it should not actually be a dangling pointer anymore. Yes, it's uninitialized, so you've lost all of the data you had stored in it (it's now garbage data), but it shouldn't cause any memory access issues.

  • Cumhur

    what does


    • nascardriver

      Hi Cumhur!

      Any number except 0 evaluates to true. If you apply the operator! this gets inverted. So everything but 0 evaluates to false.

      Try to use the later variant to make your code easier to understand.

  • Topherno

    Hi again Alex,

    In 9.12, the following line of code was shown:

    According to this section the copy constructor will be used here since a new Fraction object "six" is being created. But won't operator= be called instead since there's a "=" in the line? I'm confused how C++ knows to call the copy constructor even when operator= is called. Does it have something to do with the fact that the above line of code is, as stated in 9.12, "evaluated the same way as":

    i.e. the compiler does some kind of conversion from an operator= call to a copy constructor call?

    • Alex

      Although initialization and assignment both use =, the compiler is smart enough to know whether we're initializing a new variable or assigning a value to an existing one. It can therefore call the appropriate function.

      Since Fraction six is being defined on this line, this is an initialization, not an assignment. Initializations use constructors, whereas assignment uses operator=. It's a little misleading, since you may assume that the = literally means call operator=, but in this context, = is just part of the syntax for initialization, not an actual operator call. I suppose it's better than having to use a different symbol for initialization and assignment!

  • Jan Perme

    Hello Alex. Would it be also OK, if I put const in front of "Fraction& operator= (const Fraction &fraction);". Like so: "const Fraction& operator= (const Fraction &fraction);". Since "=" operator is evaluated from right to left, it means that it doesn't really matter if reference or const reference gets returned. Right ? No extra benefit there, I'm basically just curious 'bout it. I've tried it out in Eclipse with mingw and it looks like it works alright. But I need to be sure, that I understand it correctly. I'm sorry if I've missed out anything, that was already mentioned in previous chapters, and bringing this up again. Many thanks in advance. Jan

    • Alex

      No, you shouldn't do this, because then a statement like a = b = c wouldn't work.

      • Jan Perme

        Hello Alex. How does then the code below work ? The result is tripple 9/5 fraction. Notice, that I'm using const in front of the assignment operator declaration and definition. Thanks for clarification.

        class Fraction {
            int m_numerator;
            int m_denominator;

            // Default constructor
            Fraction(int numerator=0, int denominator=1) :
                m_numerator(numerator), m_denominator(denominator) {
                assert(denominator != 0);

            // Copy constructor
            Fraction(const Fraction &copy) :
                m_numerator(copy.m_numerator), m_denominator(copy.m_denominator)
                // no need to check for a denominator of 0 here since copy must already be a valid Fraction
                std::cout << "Copy constructor called\n"; // just to prove it works

            // Overloaded assignment
            const Fraction& operator= (const Fraction &fraction);

            friend std::ostream& operator<<(std::ostream& out, const Fraction &f1);


        std::ostream& operator<<(std::ostream& out, const Fraction &f1) {
            out << f1.m_numerator << "/" << f1.m_denominator;
            return out;

        // A simplistic implementation of operator= (see better implementation below)
        const Fraction& Fraction::operator= (const Fraction &fraction) {
            // do the copy
            m_numerator = fraction.m_numerator;
            m_denominator = fraction.m_denominator;

            // return the existing object so we can chain this operator
            return *this;

        int main()
            Fraction f1(5,3);
            Fraction f2(7,2);
            Fraction f3(9,5);

            f1 = f2 = f3; // chained assignment

            cout << f1 << endl;
            cout << f2 << endl;
            cout << f3 << endl;

            return 0;

        • Alex

          Consider f1 = f2 = f3. This evaluates as f1 = (f2 = f3). f2 = f3 calls function Fraction::operator= with f2 as the implicit object, so when we return *this, we're actually returning f2 after f3 has been assigned to it. Then the remaining expression is f1 = (f2), which works as expected.

          So this works because f2 gets f3's value, and then f1 gets f2's value.

          • Jan Perme

            Exactly my point. But notice, I've used const in front of assignment operator method and it works. Ergo, my primary statement: "Would it be also OK, if I put const in front of "Fraction& operator= (const Fraction &fraction);"" is correct, right ?

            • Alex

              Aah, sorry, I missed the actual question you were asking. This will most likely be fine. But I think it's better to return a non-const reference, otherwise statements like this won't compile: (x = y) = z;

              Also, the C++ standard library uses non-const reference return values here, and I assume they've mulled whether const or non-const is better.

  • Jakob

  • Du Ang

    Hi, Alex,
    Why I didn't get an error with the self-assignment code? It just prints "Alex". I am trying the example codes on a Mac with gcc/g++ v4.2.1.


    • Alex

      Accessing deleted memory results in undefined behavior. In this case, it appears that your "undefined behavior" is still producing the correct output (at least temporarily). That can happen, and when it does, it can make the problem hard to debug.

      • Du Ang

        I add some codes into the assignment operator overloading function for debugging. It seems that it produced the correct output because the allocated memory was just the deleted,  which are not override by other operations. At first I print both the c-string m_data's addresses, and check they are same; then I do some extra operations to allocate the memory and released immediately. Now the output is not "Alex" anymore, it's the content the last time I modified.

  • loveu

    hi alex!

    why the parameter "data" is treated like an array, is this because the compiler assumes that if assigned a string using "" the char pointer becomes a pointer to a char array?
    hence the parameter is actually :
    const char *data[]=""

    • loveu

      sorry i realised that this was a declaration for a C-style symbolic constant

      • loveu

        but how do we know whether the compiler treats it as a C-style symbolic constant string or a normal C-style string since the memory allocation is different for the two yet the syntax is so similiar

        • Alex

          data is just a pointer that holds an address. It can hold the address of either a C-style symbolic constant, or a normal C-style string. It doesn't care about how the memory it points at was allocated.

    • Alex

      Most often, we expect const char* to be C-style strings, which are arrays of char. However, note that there's nothing stopping the user from passing the address of a single char into this function, which will cause it to not work correctly (unless the char is '\0').

      It's actually the equivalent of const char data[]="". That might a better syntax to use here, as it more explicitly indicates that an array is expected.

  • Dai Nguyen

    MyString& operator= (const MyString &str);


    I don't understand why there is a "&" after MyString in the code above (overload assignment)?

    Yours sincerely,
    Dai Nguyen

    • Alex

      The & makes the MyString parameter and return value a reference, to prevent making copies of the MyString when MyString is passed as a parameter or returned to the caller.

      Please review the lesson on references, passing values by reference, and returning values by reference for more information.

  • Sai Krishna

    Hi Alex,
    In the following example,

    The following line would call the copy constructor as employee object is being created. Isn't it ?

    • Alex

      Yes, my mistake (since I didn't overload the copy constructor for these examples). I've updated the example to do an assignment rather than a copy construct.

  • Matt

    Under "Issues due to self-assignment", in the code for your overloaded operator<< function, you wrote:

    "std::ostream& operator<<(std::ostream& out, const MyString &s)
        std::cout << s.m_data;
        return out;

    Did you mean to output to "out" instead of "std::cout"?

    If so, out of curiosity, could you explain what would happen inside of this function call the way it is written now? I'm having trouble conceptualizing the flow of data here, and why it would matter whether we use "out" or "std::cout".

    • Alex

      Yes, I meant out.

      If operator<< was called with std::cout as the std::ostream parameter, then there would be no difference. But as you'll learn later, there are other std::ostream objects that could be used here, and if one of those had been used, s.m_data would have printed to the console rather than wherever that other object was pointing.

  • damiano


    shouldn't you use delete[] operator instead? Thanks

  • Vijay

    I think this operator overloading chapter needs one more article "overloading new and delete operator". It would be great, if we throw some light on it.

    • Alex

      Thanks for the thought! Overloading new and delete is more of an advanced topic. Would be fun to explore that one some day, but most people don't write their own allocators (and the ones that do probably aren't going to come here to learn how to do so). 🙂

  • Peter

    Hi Alex,

    Why does the code below work without the overloaded operator=?

    how is that differ from




    • Alex

      This is an initialization, so operator= wouldn't be called. Here's what happens:
      1) peter + wendy is evaluated first.
      2) You've overloaded operator+ to cause peter + wendy to return an object of type Hand.
      3) Object two is then constructed (using the copy constructor) with the object returned from operator+ as the argument.

      • Peter

        Thank you!
        I really like your comprehensive quizzes because they really help me review what I've learned. Since you don't have the comprehensive quiz for chapter 9 or 10, I have been working on extending the blackjack example from before.  

        I was wondering if you wouldn't mind taking a look at my code and comment on it especially errors in logic? (Once I'm done with it that is)

        It is more than a few hundred lines long and several files so I don't think it would be appropriate to post it on here. What would be an appropriate way to get my program to you?

        Either way I very much appreciate all of this!

        • Alex

          Drop me a line via the comment form in the About / Contact section.

          • Peter

            Hey Alex,

            I'm done with the blackjack example.  I dropped you a line via the comment form a while back but haven't heard from you.  Was wondering if you still would want to take a look?

            • Alex

              Hey Peter,

              I've been slammed in real life, and have barely had time to respond to the comments here. I'll try to look at your code soon but I'm not sure when I'll be able to get to it. Sorry. 🙁

              • Peter

                No problem!
                I completely understand.  When you do have sometime and willing, can you send me an email and i'll get my code to you?
                Thank you very much!

  • dmanniteaux

    Hi Alex,

    Can you explain further why in the code:

    Cents& operator= (const Cents &cSource);

    We require operator= to be passed by reference?

    I am assuming it's similar to the explanation of " .. Second, the parameter MUST be passed by reference, and not by value. Can you figure out why?" for the copy constructor part but it would be helpful if you could go into the same detail with this case as well so I can understand 🙂


  • Joris

    Can you explain how self-assignments can show up in realistic code? Could they be auto-generated somehow?

    I feel maybe an assert should be appropriate if it is a real issue to get rid of them :-/

    • Self-assignments aren't common (particularly in string classes) but it is possible to inadvertently get them in other cases (I can't think of any good examples).

      There's really no reason for a self-assignment to fail. The generally-intended end-result of the following statement:

      is that "a" should equal whatever it did before this statement (unless you overloaded operator= to do something weird, like reference counting).

      So we just special-case the self-assignment case and go on with life. 🙂

  • kuldeep

    Hi Alex,

    This tutorial was really helpful, I've one doubt, is it necessary to have assignment operator ,if copy constructor is already present, if we are sure that we are not using any assignment ( only instantiating the new object from existing one, in this case only copy constructor is enough rt ? ), do we still need to overload assignment operator ?

    • No, it's not required to have an assignment operator (if you don't create one, the compiler will create one for you and it will do a shallow copy). However, this is generally a bad idea because when you look at your code in 3 months you're likely to forget you didn't overload the assignment operator and then when you try and use it, you won't get the results you expect.

  • Tom

    Hello again Alex -

    I am having trouble grasping when and where to use *this. I will go back and re-read that chapter, but it occurs to me that it might help me (and others) if you had a symbolic diagram of the stack so I could clearly see what's going on when *this is returned by a function.

    Thanks - this website is a great intro to C++.

    • "return *this" simply returns the object that the member function is working with to the caller.

      Thus, if you called:


      and someMemberFunction() returned *this, someMemberFunction() would return foo.

      The hardest thing for most people seems to be just understanding what the this pointer is doing in the first place. The actual return mechanics are the same as with any other return value.

      • mslade

        This confused me for a bit, too, so I'll offer my understanding that it might help someone else.

        Returning *this will dereference the "this" pointer, and instead return the actual object itself. What I got tripped up on is why it wasn't thus creating a copy of this and returning that. The answer is because this function returns a Cents& (reference). As a result, the object is not copied and instead the capturing value gets the proper object.

  • jinendra

    Why cant we overload assignment operator using a friend function.
    The operators (), [], -> and = can be overloaded only as class members; all other overloaded operators can (also) be implemented as friends

    • Alex

      If you could define operator= as a non-member, then that also means you could define the overridden operator= local to a file. That could lead to inconsistencies, where operator= used the default behavior everywhere except in that one file.

      Forcing operator= to be a member avoids this situation.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]