(Tutorial) Defining and Overloading Operators in C++
Introduction
Ability to overload operators is One of the powerful features of C++. Almost every operator in C++ can be overloaded to provide custom functionality that will give your classes greater flexibility and allow then to behave as other programmers would expect them to.
Operators in C++
operators are special functions that are used to perform operations on data without directly calling methods each time. Common operators that you should be familiar with include +, -, *, /, <<, >>, and so on.
Member vs. Non-member operators
-
Member operators are operators that are implemented as member functions (methods) of a class.
-
Non-member operators are operators that are implemented as regular, non-member functions.
A basic example: Fraction
#include <iostream>
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction( int num, int denom );
void print( const std::ostream& os ) const;
};
Fraction is a simple class that represents a number as a fraction containing a numerator and a denominator. These are set via the constructor as seen in the declaration above. This tutorial assumes basic knowledge of C++ and classes, so I won't show the definitions for the constructor and the print method. You can assume that print() will output the fraction in the form "2/5".
Syntax
The syntax for overloading operators is the same as it is for declaring a function or method:
return-type operator operator-to-overload ( parameters );
Defining and overloading + and +=
#include <iostream>
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction( int num, int denom );
void print( const std::ostream& os ) const;
Fraction operator+( const Fraction& other ) const;
};
Conclusion
You should now have a solid understanding of how operators work in C++ and how they can be defined and overloaded to allow your classes to function more like primative data types. You should understand the different between unary and binary operators, and well as when to implement operators as member functions versus non-member functions.
I always welcome questions or feedback about this tutorial. Simply post a reply or PM me; I'm glad to help!
For Full Detail about this Tutorial Click Here
Courtesy:- www.ozzu.com

