0

When I am trying to run this code I am getting the output to be zero which isn't expected, according to what I have defined I should get a -1 rather than a 0,I have tried changing the values of x,I have tried looking up for the garbage value if any. What you guys think?

#include<iostream>
using namespace std;

class nf {
    int x;
public:
    nf() {
        x=1;
    }
    nf(int a) {
        a=x;
    }

    friend nf operator ++(nf n1) {
        n1.x=-n1.x;
    }
    void display() {
        cout<<x;
    }
};

int main()
{
    nf obj(1),obj2;
    obj2=++obj;
    obj2.display();
}
ivpavici
  • 1,117
  • 2
  • 19
  • 30
Saubhagya
  • 155
  • 12

1 Answers1

0

Sorted.

#include<iostream>
using namespace std;
class nf{
    int x;
    public:
    nf()
    {
        x=1;
    }
    nf(int a){
        x=a;
    }
friend nf operator ++(nf &n1)
{
    n1.x=-n1.x;
}
void display()
{
    cout<<x;
}



};
int main()
{
 nf c1;
 ++c1;
 c1.display();

}
Saubhagya
  • 155
  • 12
  • `friend nf operator ++(nf &n1){ n1.x=-n1.x;}` -- Undefined behavior. An `nf` is supposed to be returned, but nothing is returned. – PaulMcKenzie Mar 06 '17 at 20:40