Unary Operator Overloading In C++ - C++ Programming Tutorial
C++ Course / Polymorphism / Unary Operator Overloading In C++

Unary Operator Overloading In C++

BLUF: Mastering Unary Operator Overloading In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Unary Operator Overloading In C++

C++ is renowned for its efficiency. Learn how Unary Operator Overloading In C++ enables low-level control and high-performance computing in the tutorial below.

It constitutes polymorphism when we redefine an operator to perform a similar action on instances of the identical class. Unary operators alone cannot be employed with class instances as they lack an understanding of class member variables, leading to compilation issues. Operator overloading is implemented for custom data type (class object) functionalities to assign custom meanings to operators.

We can implement unary operator overloading in C++ by defining a custom operator function within the class or by utilizing a global friend function specifically designed for the operator.

What is a Unary Operator in C++?

C++ offers a diverse set of operators for executing mathematical and logical tasks on numeric values. An extensively utilized operator in this category is the unary operator. Unary Operators are crucial for operations involving a solitary operand. In contrast to binary operators, unary operators operate effectively without the necessity of two operands for computation.

The unary operator is employed to ascertain the updated value of a solitary operand or variable. When utilizing unary operators, the operand is interchangeable between the prefix or postfix position. Unary operators exhibit equal precedence, right-to-left associativity, and come in various forms.

Syntax:

The syntax for overloading unary operators in C++ is as follows:

Example

class className {
    ...
    public
returnType operator <symbol> (<parameters>) {
           ...
       } 
    ...
};

Here are a few examples of unary operators:

  • Decrement operator (--),
  • Increment operator (++),
  • Logical not operator (!),
  • Unary minus operator (-),
  • Address of (&), etc.

Let's take an instance to explain the concept of overloading unary operators in C++.

I). Unary Operator Overloading for User-Defined Classes:

Example

Let's take an example to understand how to define a complicated user-defined class in C++:
#include <iostream>

using namespace std;

class Complex {
private:
    int real, imag;

public:
Complex() {
        real = 0;
imag = 0;
    }

Complex(int r, int i) {
        real = r;
imag = i;
    }

    // Overloading unary minus operator
    Complex operator-() {
        return Complex(-real, -imag);
    }

    void display() {
cout<< real << " + " <<imag<< "i";
    }
};

int main() {
    Complex c1(3, 4);
    Complex c2 = -c1;

cout<< "Original complex number: ";
    c1.display();
cout<<endl;

cout<< "Negated complex number: ";
    c2.display();
cout<<endl;

    return 0;
}

Output:

Output

Original complex number: 3 + 4i
Negated complex number: -3 + -4i

II. Overloading the class Member function for the unary minus (-) operator

Let's consider an illustration to grasp the process of declaring the class Member function for the unary minus (-) operator in C++:

Example

#include <iostream>

using namespace std;

class MyNumber {
private:
    int value;

public:
MyNumber() {
        value = 0;
    }

MyNumber(int val) {
        value = val;
    }

    void display() {
cout<< "Value: " << value <<endl;
    }

    // Overloading unary minus (-) operator using class member function
MyNumber operator-() {
        return MyNumber(-value);
    }
};

int main() {
    // Instantiating a MyNumber object num1 with value.
MyNumber num1(7);

    // Printing the num1 object in the output.
cout<< "num1: ";
    num1.display();

    // Invoking the overloaded unary minus (-) on num1 object and
    // storing the returned object in a new num2 MyNumber object.
MyNumber num2 = -num1;

    // Printing the num2 object in the output.
cout<< "num2 (after unary minus): ";
    num2.display();

    return 0;
}

Output:

Output

num1: Value: 7
num2 (after unary minus): Value: -7

III. Overloading the global friend function's unary minus (-) operator

Let's consider an instance to grasp the process of declaring the unary minus (-) operator within a global friend function in C++:

Example

#include <iostream>

using namespace std;

class Complex {
    private: int real,
img;

    public: Complex() {
        real = 0;
img = 0;
    }

Complex(int r, int i) {
        real = r;
img = i;
    }

    // Printing the complex number in the output.
    void print() {
        int newImg = img<0 ? -img : img;
cout<< real << (img<0 ? " - " : " + ") << "i" <<newImg<<endl;
    }

    // Making a friend function with the global overloaded unary minus operator.
    friend Complex operator - (const Complex &obj);
};

// Overloading the unary Minus (-) operator as a global function

Complex operator - (const Complex &obj) {
    return Complex(-(obj.real), -(obj.img));
}

int main() {
    Complex c1(-5, -4);

cout<< "c1 = ";
    c1.print();

    Complex c2 = -c1;

cout<< "c2 = ";
    c2.print();

    return 0;
}

Output:

Output

c1 = -5 - i4
c2 = 5 + i4

Explanation:

  • In this example, we created a friend function in the Complex with a globally overloaded minus (-) unary operator
  • A friend function in C++ is a unique function that is not a member of a class but has access to its protected and private data .
  • A global friend function that can access the real and image variables has been given that has an overloaded definition for the global minus (-) operator outside of the Complex class . After using the c2 object and the unary minus(-) operator in the main function, it is called.
  • Conclusion:

  • In C++, unary operators are used for operations with a single operand or variable .
  • Here are a few instances of unary operators: Unary minus operator (-), Logical not operator (! ), Increment operator (++), Decrement operator (- -),
  • In C++, polymorphism (known as unary operator overloading) is used to make an operator more capable of carrying out similar operations on objects belonging to a class.
  • We use operator overloading to give operators a user-defined meaning for user-defined data type (object of a class) operations.
  • We may use unary operator overload by defining a new operator function in the class itself or by utilizing the global friend function made for the operator function.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience