Skip to main content Accessibility help
Internet Explorer 11 is being discontinued by Microsoft in August 2021. If you have difficulties viewing the site on Internet Explorer 11 we recommend using a different browser such as Microsoft Edge, Google Chrome, Apple Safari or Mozilla Firefox.

Chapter 13: Operator Overloading

Chapter 13: Operator Overloading

pp. 699-769

Authors

, Vidyalankar Institute of Technology
  • Add bookmark
  • Cite
  • Share

Summary

Overview

All the operators in C++ are designed to operate with the basic data types only. For example, an arithmetic operator + can be used to perform addition of integers, floats, doubles etc. but cannot be used to perform addition of user-defined objects. Let's say if we create a class Point to represent points in Cartesian coordinate system, we are not able to perform addition of two Point objects using operator + like we do it for primitive types. Recall from Chapter 11 section 11.10 that addition of Point objects P1 and P2 is performed using a function add() defined inside the class. We performed the addition of two points P1 and P2 by making a call to add() as follows:

P3=P1.add(P2);

The function is invoked by P1 passing P2 is passed as an argument, the result of addition is stored in object P3, which gives the x and y coordinate values of the resultant point. The addition of Point objects is performed using a member function add(), merely because the arithmetic operator + cannot be used to perform addition of user-defined objects. The basic principle of operator overloading is to extend the capability of C++ operators in order to use them with user-defined types in the same way and with the same syntax as with basic types. When we say that classes are used to create user-defined data types, it is a fair expectation that the operation with user-defined objects should be performed in the same way as they are performed with primitive types.

If we overload operator + in class Point, we will be able to perform addition of Point objects as follows:

P3=P1+P2;

Making use of operator + to add Point objects makes the statement very easy to read and understand when compared to the former statement. Operator overloading is essentially used by the programmers to create programs with a friendly syntax. Clearly it is not a necessity, but it provides great luxury to the programmers to read and maintain the program.

About the book

Access options

Review the options below to login to check your access.

Purchase options

eTextbook
US$550.00
eTextbook
US$110.00

Have an access code?

To redeem an access code, please log in with your personal login.

If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.

Also available to purchase from these educational ebook suppliers