
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
What is overloading a unary operator in C++?
The single operators operate on one quantity and following are the samples of single operators − - The increment ( ) and decrement (--) operators. 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, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--.
Following example explain how bang(!) 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 bang(!) operator Distance operator!() { feet = -feet; inches = -inches; return Distance(feet, inches); } }; int main() { Distance D1(3, 4), D2(-1, 10); !D1; D1.display(); // display D1 !D2; // apply negation D2.display(); // display D2 return 0; }
Output
This will give the output −
F: -3 I:-4 F: 1 I:-10
- Related Articles
- Overloading unary operator in C++?
- Overloading unary operators + in C++
- Unary operator in C++
- What is Unary Negation Operator (-) in JavaScript?
- What is Unary Plus Operator in JavaScript?
- Overload unary minus operator in C++?
- Rules for operator overloading in C++
- Overloading array index operator [] in C++
- Java Unary Operator Examples
- Increment ++ and Decrement -- Operator Overloading in C++
- How to use Operator Overloading in C#?
- How to implement operator overloading in C#?
- What is overloading in C#?
- What are the basic rules and idioms for operator overloading in C++?
- What is method overloading in C#?

Advertisements