Introduction

 < Day Day Up > 



In C++ you can add meaning to certain language operators so they behave in expected ways when applied to your user-defined type objects. Adding meaning to operators in this fashion is referred to as operator overloading.

You have already seen many examples of operator overloading in action. Take the declaration and use of pointers as an example. To declare a pointer you use the * operator. To dereference a pointer you use the same operator, which is the same operator you use to multiply two number types. The compiler knows, by examining the context in which the operator is used, which version of the operator to call.

Overloaded operators provide an elegant way to manipulate user-defined type objects. The decision regarding which operators should be overloaded to manipulate a particular class of objects is a function of your design. This chapter will help you understand how to overload C++ operators and show you when it is appropriate to overload the different types of operators in the context of your design.

Although I will show you all of the operators that can be overloaded in C++ I will not show you an example of how to overload every single operator. Many operators can be grouped together, like the binary arithmetic operators. Knowing how to overload one in the group leads to an understanding of how to overload the others. Most of the operators can be treated in this fashion. Others will be left to the student as an exercise for further independent study.

Operator overloading is one of my favorite C++ language features. It is one of the 'cool' things a C++ programmer knows how to do. When you get the hang of operator overloading and get used to thinking of when and how to incorporate overloaded operators in your class design, you will miss not being able to overload operators when programming in a language like Java. Overloaded operators, used in the right context, lead to cleaner, easier to read and understand code.



 < Day Day Up > 



C++ for Artists. The Art, Philosophy, and Science of Object-Oriented Programming
C++ For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504028
EAN: 2147483647
Year: 2003
Pages: 340
Authors: Rick Miller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net