Hi. Could you please guide me in performing operator overloading of Unary operator? Just explain the method with an example. Please add the explanation.

Recommended Answers

All 4 Replies

You mean the + operator?

class MyClass
{
private:
   int x;
public:
   MyClass() {x = 0;}
   MyClass operator+(int x)
   {
      MyClass n = *this;
      n.x = n.x + x;
      return n;
   }
};

Are you referring to the addition operator (operator+) or to any operator that takes only one operand?

There are 4 ways to overload operators, and which specific method you use depends on if it's a Unary operator or a Binary operator and whether it's a member function or not.

To overload a non-member Unary operator, the operand becomes a parameter to the operator function:

struct example {
  int anInt;
};

//Overload the Unary minus for the "example" struct:
void operator- (example &o1) {
  o1.anInt = -o1.anInt;
}

Fbody's solution is a bit bad because it changes the semantics of the built-in operator-. Consider it.

struct example {
  int anInt;
};
 
//Overload the Unary minus for the "example" struct:
void operator- (example &o1) {
  o1.anInt = -o1.anInt;
}

#include <iostream>

void Print(example e)
{
   std::cout << e.anInt;
}
int main()
{
example e1; 
e1.anInt = 4;
example e2 = -e1; //compile error, operator - is void;
Print(-e1) //compile error again, same reason.
}

Much better is, when operator - returns an object.

struct example {
  int anInt;
};
 
//Overload the Unary minus for the "example" struct:
example operator- (const example &o1) { //note the const, good style
  example ret;
  ret.anInt = -o1.anInt;
  return ret;
}

also , the operator can be a member of the class, like this

struct example
 {
  int anInt;
  example operator - () const //note that there are no parameters, well the actual parameter is *this
  {
   example ret;
   ret.anInt = -this->anInt;
   return ret;
  }
};

Apologies.

Generally your methods are better, and how I would normally do it. I looked up "overloading C++ unary operators" before I posted just to check some things and I got a link to an IBM website. I found the examples on that page rather odd, so I went to another page (I don't remember what it was) and theirs were similarly formatted. I would have thought IBM's examples would be more authoritative and/or accurate than that, but upon further contemplation I can see the error in them.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.