Rules for Operator overloading in C++In this article, you will learn about the rules for operator overloading in C++. There are several rules for operator overloading in C++. Some main rules are as follows: 1. SyntaxOverloading an operator is defined by defining a function with the operator keyword followed by the Operator to be overloaded. For example: 2. Logical and Consistent ImplementationOverloaded operators should be implemented logically and consistently with the expected behaviour of the corresponding built-in operators. Avoid overloading operators in a way that might lead to confusion or unexpected behaviour. 3. Number of OperandsMost unary and binary operators can be overloaded. Unary operators take one operand (e.g., +, -, ++, --). Binary operators take two operands (e.g., +, -, *, /). 4. Precedence and AssociativityThe precedence and associativity of the relevant built-in operators are passed down to overload operators. Overloading cannot alter an operator's precedence and associativity. 5. Types of Operand and ReturnAn operand for an overload operator must be of at least one user-defined type. The return type should usually reference the class or the class type for assignment operators. 6. Overloading RestrictionsSome operators cannot be overloaded, or their behaviour cannot be changed significantly. For example, (member access), .* (member pointer access), :: (scope resolution), ?: (ternary conditional), sizeof, and typeid. 7. Overloading as a Member FunctionWhen overloaded as a member function, the left operand is implicitly the calling object. Binary operators must have at least one operand of the user-defined type. Example: 8. Overloading as a Non-Member FunctionBoth operands are supplied as arguments when overloading as a non-member function. Example: 9. Friend Function OverloadingOperator overloading can also be handled using a friend function if it requires access to private members. Example: 10. Common Operators to OverloadSome commonly overloaded operators include +, -, *, /, %, ==, !=, <, >, <=, >=, +=, -=, *=, /=, ++, --, =, <<, and >>. 11. Overloading << for OutputOverloading << allows you to define how objects of your class should be displayed using std::cout. Example: Example:Output: Complex Number 1: 2.5 + 3.5i Complex Number 2: 1.5 + 2.5i Sum: 4 + 6i Explanation: 1. Definition of Class (Complex)
2. Overloaded Operator + (Member Function)
3. Overloaded Operator << (Friend Function)
4. Main Function
5. Output
Next Topicstd::adjac?nt_diff?r?nc? in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India