-1

I have the following program:

#include <iostream>

using namespace std;

class N {
public:
    float x;
    N(){ x = 3.0; }
    N(float y){ x = y; }
    N &operator=(float f){ return *new N(f); }
};



int main(){
    N a;
    a = 2.0;
    cout << a.x;
    return 0;
}

I am expecting for the result to be 2 (because of definition of operator=), but instead it gives me 3 (like there is no line a = 2.0). Can someone, please, explain me why is this happening, what is wrong with definition of 'operator='? Thank you...

Ray
  • 33
  • 1
  • 7
    why are you returning a reference to `*new N(f)`? `operator=` is supposed to return `*this`… Also, you're **not changing anything** in the assignment operator. Why would you even expect this to work? – The Paramagnetic Croissant Mar 03 '15 at 12:01
  • 1
    The copy-assignment operator is for assignments to *`this`*, you're not supposed to create another object. – Some programmer dude Mar 03 '15 at 12:03
  • 1
    You need a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn some basics. – Baum mit Augen Mar 03 '15 at 12:03
  • Simplify it: `N &operator=(float f){ x = f; return *this; }` – hlscalon Mar 03 '15 at 12:06
  • Why negative votes? He posted a compiled example. – amchacon Mar 03 '15 at 12:07
  • @ 1nflktd I am not trying to get value of 2, I am just asking why it is not returned. If I omit the line ''N &operator=(float f){ return *new N(f); }'', I will get the result of 2. I am just wondering what is going on here, because there is no compilation error or something like that. – Ray Mar 03 '15 at 12:11
  • @Ray they have told you why – zoska Mar 03 '15 at 12:12
  • @Ray Your program is syntactically correct, so compiler doesn't give errors. – amchacon Mar 03 '15 at 12:12
  • To you question " why it is not returned" - the value is returned from operator = but you don't use it. if you write cout << (a=2.0); then 2 will printed. (Of course, don't do this, do what everyone advised you) – Ophir Gvirtzer Mar 03 '15 at 12:38

2 Answers2

2

Your copy assignment operator should be setting the value of x, then returning a reference to *this, like so:

N &operator =(float f) { x = f; return *this; }

Instead, your copy assignment operator is constructing a new instance of N on the heap, and returning a reference to that.

0

You shouldn't use new, C++ isn't java.

N& operator=(float f)
{ 
    x = f; 
    return *this; 
}

Try this.

amchacon
  • 1,891
  • 1
  • 18
  • 29