unary operator overloading using non member non friend function

can anyone help me how to do unary operator overloading using non member non friend function?
Last edited on
There's multiple unary operators in C++, each with different techniques for proper overloading.

Here's an example for the unary negation operator (-).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Example program
#include <iostream>

class Foo {
    
  public:
    Foo(int a)
    : a(a) {}   
    
    int a;
};

// unary operator overloading using non-member, non-friend function
Foo operator-(const Foo& foo)
{
    return Foo(-foo.a);
}

int main()
{
    Foo foo(42);
    std::cout << foo.a << std::endl; // 42
    
    foo = -foo; // unary negation operator being used
    
    std::cout << foo.a << std::endl; // -42 
}
Topic archived. No new replies allowed.