2

I am new to c++, and I was recently trying to understand overloading functions. I have questions about references in operator overloading. I get that CBoys& is reference to class CBoys, but i dont see difference in following 5 overload of operator =.

class CBoys{
//operator=(const CBoys&);
//operator=(const CBoys);
}
// CBoys& operator=(const CBoys&);
// CBoys operator=(const CBoys&);
// CBoys& operator=(const CBoys);

Thx for help

2
  • I edited question a bit Commented Apr 8, 2014 at 18:25
  • operator= must always be a member function, so the last three are invalid. Commented Apr 8, 2014 at 19:40

1 Answer 1

2

Well, for starters,

operator = (const CBoys&);

and

operator = (const CBoys);

are invalid. The only time when you omit the return type (operators are just like functions) is when you are overloading conversion operators. e.g.

operator bool();

when defined within your type will create a method to implicitly convert your type to bools.

As for the rest, they all differ based on their return types and the parameters they take in. The first one, CBoys& operator=(const CBoys&); takes in a reference to a constant CBoys and returns a reference to a CBoys. The second one returns a CBoys by value. The third one, while fine, makes a copy of the CBoys you pass into it (the object on the right hand side.)

Long story short, the constness and reference-ness of the parameters to an operator overload mean the same thing that they do in regular function declarations.

Implementing a copy assignment operator overload is typically pretty straight-forward:

class CBoys {
    // stuff
public:
    CBoys& operator = (const CBoys& rhs) {
        CBoys temp(rhs); // make a copy.
        using std::swap;
        swap(*this, temp); // and swap the old *this with the new object.
        return *this; // return the object by-reference.
    }
};

This allows us to use the assignment operator in a straight-forward way with no surprises, as it behaves like the assignment operator for built-in types. For more information on copy assignment operators, see here: http://en.cppreference.com/w/cpp/language/as_operator

I hope this helps your understanding.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.