Overloading unary minus operator without member function

  c++, operator-overloading

Consider the following program:

//Operator overloading of unary minus operator- with and without member function

#include <iostream>
using namespace std;
class test{
    int x;
    public:
    test(){

    }
    test(int h){
        this->x=h;
    }
    friend void operator- (test);
    void showData(){
        cout << x << endl;
    }
};
void operator- (test a){
     test *ptr=&a;
     ptr->x=-ptr->x;
}
int main(){
    test t1(7);
    operator-(t1);
    t1.showData();
    return 0;
}

On executing, this prints 7 instead of -7 on online compilers as well as Visual Studio Code on machine. Can someone explain what’s wrong?

Source: Windows Questions C++

LEAVE A COMMENT