-2
struct Object{
    size_t num;

    Object(size_t s){
        num = s;
    }

    Object(string str){
        num = 1;
    }

    Object& operator = (const Object& b){
        cout << "assignemnt constructor called" << endl;
        return *this;
    }
};


int main ()
{
    Object b2{ 5 };
    Object b3("str");
    b2 = b3;
    b3 = Object(2);   //<-------------how can you set b3 to be Object(2)?
}

I'm trying to set an object to be equal to a new object. but b3 doesn't change in this example. Can anyhelp help me understand how I can get b3 to be a new object(2). Thanks

conterio
  • 1,087
  • 2
  • 12
  • 25
  • 5
    Well, you implemented an assignment operator, and you get exactly the behaviour you implemented. You have nobody to blame but yourself. – Kerrek SB Aug 05 '15 at 17:26
  • 1
    See [here](http://stackoverflow.com/questions/4421706/operator-overloading) – yizzlez Aug 05 '15 at 17:26

1 Answers1

1

Your assignment operator doesn't really do any assigning. What you probably want to do is this:

Object& operator = (const Object& b){
    cout << "assignemnt constructor called" << endl;
    num = b.num;
    return *this;
}

Also, the text "Assignment constructor called" is incorrect. This is the assignment operator, not the copy constructor. When you do:

b3 = Object(2);

you invoke the assignment operator. Conversely, when you do:

Object b3 = Object(2)

you invoke the copy constructor. A subtle but important difference.

Carlton
  • 4,217
  • 2
  • 24
  • 40