0 votes
126 views
in Programming by (98.9k points)
edited
Write a c++ program for overloading of unary + operator?

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer
#include <iostream>

using namespace std;

class Number {
 private:
 int num;

 public:
 Number() {
 num = 0;
 }

 Number(int n) {
 num = n;
 }

 // Overload unary + operator
 Number operator+() {
 return Number(num);
 }

 void display() {
 cout << "Number: " << num << endl;
 }
};

int main() {
 Number n1(5), n2;

 // Call the overloaded unary + operator
 n2 = +n1;

 n1.display();
 n2.display();

 return 0;
}

In this program, we define a Number class that has an int data member num. We also define a default constructor and a parameterized constructor to initialize the num member.

The Number class overloads the unary + operator by defining a member function named operator+(). This operator function returns a Number object, which is the original object itself. In this case, the overloaded + operator does not modify the object, but simply returns it.

In the main() function, we create two Number objects n1 and n2. We then call the overloaded + operator using the syntax +n1. The result of this operation is assigned to n2.

Finally, we display the values of n1 and n2 using the display() member function.

Output:

Number: 5
Number: 5

As we can see, the overloaded + operator does not modify the object, but simply returns a copy of it. In this case, n2 is a copy of n1, since the overloaded + operator returns the original object itself.

Related questions

0 votes
1 answer 149 views
0 votes
1 answer 120 views
0 votes
1 answer 1.5k views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

559 users

...