How do I return a temporary result object?

This is a discussion on How do I return a temporary result object? within the C++ Programming forums, part of the General Programming Boards category; I'm far from new to programming, and I know C very well, and I'm learning C++. But C++ isn't C ...

How do I return a temporary result object?

I'm far from new to programming, and I know C very well, and I'm learning C++. But C++ isn't C (even if it sometimes looks ever so similar), so I'm struggling a bit...

I have spent most of today coming up with a class that implements "very long integer", as part of an excercise in a C++ book. For no particular reason, there's no "answer" to this excercise in the book, and I'm sort of flumoxed on the way that I should solve this particular problem:

However, this is not good - we're returning the address of a local object temp, which is stored on the stack of the operator+ method. I have seen this done several times, but as far as I'm concerned, this object doesn't exist after the return. [It is inded not possible to use this method - it crashes with a exception due to accessing "invalid address"].

So instead, I allocate a new object using "new":
I have spent most of today coming up with a class that implements "very long integer", as part of an excercise in a C++ book. For no particular reason, there's no "answer" to this excercise in the book, and I'm sort of flumoxed on the way that I should solve this particular problem:

Daved, since I haven't even implemented a += operator (yet?), I can't use that trick - but it's a good idea for if I need to do something similar - in this case, the excercise required operator+, operator* and operator<<(ostream) and that's what I've done. [For laughs I also added operator+(int v) - just using the trick to convert v into a verylongint temp first, and then just return temp +*this.]

Adding a operator- wouldn't be too hard. operator/ would be "intersting challenge" - dividing numbers is amongs the more complex things we can do - that's why even modern processors take dozens of cycles to do that...

>> Daved, since I haven't even implemented a += operator (yet?), I can't use that trick
No worries. It's not really a trick though. It is actually better design than having separate implementations. In most cases it is not logical to have operator+ but not operator+=, so you almost always want to implement both (the obvious exception being an assignment that doesn't require both). And if you are implementing both, it is best to keep that implementation in one place to reduce bugs and maintain consistency.