Chapter 30. Overloading Assignment Operators
In This Chapter
Overloading operators — in general, a bad idea
Overloading the assignment operator — why that one is critical
What to do when you just can't be bothered with writing an assignment operator
The little symbols like +, -, =, and so on are called operators. These operators are already defined for the intrinsic types like int
and double
. However, C++ allows you to define the existing operators for classes that you create. This is called operator overloading.
Operator overloading sounds like a great idea. The examples that are commonly named are classes like Complex
that represent a complex number. (Don't worry if you don't know what a complex number is. Just know that C++ doesn't handle them intrinsically.) Having defined the class Complex
, you can then define the addition, multiplication, subtraction, and division operators (all of these operations are defined for complex numbers). Then you write cool stuff like:
Complex c1(1, 0), c2(0, 1); Complex c3 = c1 + c2;
Overloading operators turns out to be much more difficult in practice than in theory. So much so that I consider operator overloading beyond the scope of this book with two exceptions, one of which is the subject of this chapter: overloading the assignment operator. The second operator worth overloading is the subject of the next chapter.
Overloading an Operator
C++ considers an operator as a special case of a function call. It considers the +
operator to be shorthand for the ...
Get Beginning Programming with C++ For Dummies® now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.