

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Overloading unary operators + in C++
The operator keyword declares a function specifying what operator-symbol means that once applied to instances of a class. this gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
The unary operators operate on a single operand and following are the examples of Unary operators −
- The increment (++) and decrement (--) operators.
- The unary minus (-) operator.
- The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in +obj, !obj, -obj, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--.
Following example explain how plus(+) operator can be overloaded for prefix usage −
Example
#include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // Constructor Distance(int f, int i) { feet = f; inches = i; } // method to display distance void display() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded plus(+) operator Distance operator+() { if(inches == 11) { inches = 0; feet = feet + 1; } else { inches = inches + 1; } return Distance(feet, inches); } }; int main() { Distance D1(3, 4), D2(1, 11); +D1; D1.display(); +D2; D2.display(); return 0; }
Output
This will give the output −
F: 3 I:5 F: 2 I:0
- Related Questions & Answers
- Overloading unary operator in C++?
- Unary operators in C++
- Unary operators in C/C++
- Overloading Operators in Python
- What are unary operators in C#?
- What is overloading a unary operator in C++?
- What are the unary operators in Java?
- How does Overloading Operators work in Python?
- Overloading stream insertion (<<) and extraction (>>) operators in C++
- Unary operator in C++
- Plus One in Python
- Java Unary Operator Examples
- Unary or Recursive Relationship
- Overloading in C#
- Instant plus() method in Java