Chapter 30

Overloading Assignment Operators

In This Chapter

arrow Overloading operators — in general, a bad idea

arrow Overloading the assignment operator — why that one is critical

arrow Getting by without 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 such as Complex that represent complex numbers. (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 this:

  Complex c1(1, 0), c2(0, 1);Complex c3 = c1 + c2;

Whoa, there, not so fast. 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 ...

Get Beginning Programming with C++ For Dummies, 2nd Edition 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.