Lesson 16 | Tips for overloading operators |
Objective | Review some operator overloading guidelines. |
Overloading Operators in C++
Operator overloading can be misused and abused. Here is a quick review of some of the operator overloading guidelines discussed so far in this course.
When not to overload C++ Operators
Operator overloading is easily misused, so do not overload operators when such overloading can lead to misinterpretation. The domain of use should have a widely used notation that conforms to your overloading. Overload related operators in a manner consistent with C++ community expectations. For example, the relational operators <
, >
, <=
, and >=
should all be meaningful and provide expected inverse behaviors.
Use friend Functions
Generally speaking, you should overload symmetrical binary operators, such as
+
, *
, ==
, !=
, and &&
with friend
functions. Both arguments are then passed as ordinary parameters. This subjects both arguments to the same rules of parameter passing. Recall that using a member function to provide overloading for symmetrical binary operators causes the first argument to be passed via the this
pointer.
Overloading Assignment with new
Any time a class uses new
to construct objects, it should provide an explicitly overloaded operator=()
.
This advice is analogous to our rule that such a class provide an explicit copy constructor. The compiler-provided default assignment operator semantics would in most cases give spurious behavior. This leads to a suggested normal form for classes with heap-managed memory.
//Normal Form for heap managed classes illustrated
class vect {
public:
vect(); //default constructor
vect(const vect&); //copy constructor
.....
vect& operator=(const vect&); //returns lvalue
.....
};
This normal form rule applies as well to reference counted classes, such as the string
type.
The reason the operator=()
returns a reference is to allow assignment to work efficiently. This requires lvalue semantics.
Mathematical ADT Quiz