Stabilo
Stabilo

Reputation: 269

Overloading the assignment operator or use the default one?

If I have

Class A {
    int x;
};

Class B {
    vector<A> y;
    //...
};

And I want to overload the assignment operator = in B. Will using the default = operator be enough? Will it just use the = operator of vector on y member?

EDIT: say I wanted to implement something like that myself, so that b = k will work if both b and k are of type B. would I need to explicitly call the vector destructor to free the y member of b, inside the implementation?

How will it look like?

B& B::operator=(const B& b) {
    if (this == &b) {
       return *this;
    }
    y = b.y;
    return *this;
}

Will the original vector this->y destructed here? why?

Upvotes: 1

Views: 66

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Will using the default = operator be enough?

Yes, it's sufficient, unless you have any resources that need special treatment or parameters.

Will it just use the = operator of vector on y member?

Yes, the generated default assignment operator/copy constructor will call any assignment operators/copy constructors available for member variables automatically.


 B& B::operator=(const B& b) {
     if (this == &b) {
           return *this;
       }
       y = b.y;
       return *this;
 }

Will the original vector this->y destructed here? why?

Yes, it will be "destructed", since the operator=() definition of vector<A> implies to do so.

It's not really the destructor function is called, but the implementation of the assignment operator does imply the same behaviour as there would be a new instance constructed, and all of the contained member destructors will be called when the vector is cleared.

Upvotes: 4

I3ck
I3ck

Reputation: 433

If you don't have special cases (like owning pointers, or unique_ptr), you can just not-define it and use the default one. In your case it should be fine.
In case of owning pointers, you would suddenly have two objects pointing to the same data in memory, which might not be the behaviour you want (same goes for shared_ptr.
unique_ptr can't be copied, so the default assignment operator won't work in this case and you'd have to write an overload.

Upvotes: 1

Related Questions