tags:

views:

142

answers:

4

Hi!

I'm currently refreshing my C++ skills and was wondering if it is possible to assign something to *this. I know assigning to this is forbidden, but can't find the same information for my case.

An example:

class Foo {
  int x;
public:
  Foo(int x) : x(x) {}
  Foo incr() { return Foo(x+1); }
  void incr_() { (*this) = incr(); }
};

Edit: corrected incr()'s return type from void to Foo.

+6  A: 

void incr() { return Foo(x+1); }

This is invalid. You cannot return a Foo object from a function having void return type.

void incr_() { 

   (*this) = incr(); // This invokes Foo& operator = (const Foo& ) (compiler synthesized)
}

This is fine.

Prasoon Saurav
This would have been more suited as a comment than as an answer, IMO.
Etienne de Martel
@Etienne : Lemme complete my answer first. `:)`
Prasoon Saurav
You are totally right, but I simply made a mistake there. I meant the function to be `Foo incr()`.
Kolja
OK, now that the memory leak answer has enough downvotes for me to be sure, thanks a lot!
Kolja
+3  A: 

Yes, it is allowed, and it actually invokes your class' assignment operator.

Etienne de Martel
A: 

Yes, you can, if *this return value is of a datatype that has an assignment operator defined.

Franci Penov
+1  A: 

Yes, it works. And *this = x is just syntactic sugar for operator=(x).

FredOverflow