Operator Overloading


After you've been programming for a while, you get used to being able to add two numbers together with the "+" operator, subtract them with "-" operator, etc. But when you start creating your own classes, you've found that you can no longer do that, at least from what you know now.

For example, lets say that you have a burrito class, and in this burrito class you have an add_burrito method which combines the toppings from another burrito into the current burrito, to create one super burrito. However, as you begin using this class in a program, you find that you are often combining burritos in an attempt to find the supreme burrito. But typing add_burito every time is beginning to get on your nerves. You really wish you could just add them together using a "+" operator like you can with numbers, but you can't. Or can you?

This is where operator overloading comes in, which we'll delve into a bit more in the next section. Operator overloading, like classes, has no real equivalent in Pascal. It allows you to "redefine" how certain operators, such as "+" and "-", work when used with your own classes. It is called operator overloading because you are "overloading", or reusing, the same operator with a number of different possible uses, and then the compiler decides how to use that operator depending on what operands it has.


Table of Contents

Operator Overloading | Binary Operator Overloading | Unary Operator Overloading | Overloading Conversion Operators
Using Overloaded Operators | Exercises | Continuing the Journey