What is the proper way of declaring the copy assignment?

I just took a class in c++ and one of the things we learned how to do was create classes, throughout the semester we were always declaring the copy assignment with void like this (let's say we are making a fraction class)
void operator=(const fraction &);

On the last day of class my professor told us that we shouldn't use void to declare the copy assignment and that we should learn it on our own after the semester ends.

So what is the proper way to declare the copy assignment?
What about for the move assignment, should we use void there too or not?
Last edited on
The assignment operator should return a reference to this:
1
2
3
4
fraction &operator=(const fraction &) {
    // do the assignment
    return *this;
};

That allows you to say:
1
2
3
fraction a,b,c;
// set a
b = c = a;   // calls b.operator=(c.operator=(a)); 

I must admit that I don't think I've ever actually needed this property.
@dhayden, in the copy assignment do I return the fraction on the left side of the equals operator or the right side, they would be equal after I // do the assignment ? Or am I not understanding what you mean by return *this; ?
Last edited on
closed account (E0p9LyTq)
http://www.cplusplus.com/articles/y8hv0pDG/
I read the article and it explains a lot I just don't understand what the const in front of the return type is there for if we decide to include it, what is it keeping constant when I write this const MyClass& operator=(const MyClass& rhs) as opposed to this MyClass& operator=(const MyClass& rhs)?
Last edited on
It means that it returns a const reference. That prevents you from doing whacky stuff like:
1
2
MyClass a(10), b(20);
(a=b).member = 3;

Topic archived. No new replies allowed.