Functions and Objects

Operator Overloading in C++

Similar to function overloading, where functionality varies depending on different numbers and types of inputs, operators can be overloaded as well, within a class.


Syntax
/*Similar to function declaration, but with the function name operator_. _ is the operator symbol. */

//overloading the plus operator
returnType operator+ (inputVariables){
    //code to execute
}




Notes

Overloaded operators are typically used to handle behavior for when a class interacts with an operator.

If a class is passed into the overloaded operator, the operator function may need access to private members of the class. In this case, the function needs to be declared as a 'friend' function.


Example
//adding two fraction classes together
//Fraction class has a numerator, denominator field with accessors
//A new fraction class is returned with the new numerator and denominator
Fraction operator+(const Fraction& left, const Fraction& right){
    int newDenom = left.denominator() * right.denominator();
    int newNumerator = (left.denominator() * right.numerator()) + (right.denominator() * left.numerator());
    Fraction newFraction(newNumerator, newDenom);
    return newFraction;
};
     

< Functions   |   Inheritance >

© 2019 SyntaxDB. All Rights Reserved.