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"].Code:class verylongint { .... verylongint &operator+(const verylongint &a) { verylongint temp; .... // add the contents of a and this into temp return temp; } }; ... // example of how this would be used main() { verylongint a(123), b(345); cout << "a + b = " << a + b << endl; } }
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:
This works correctly, but it leaks memory, so should I decide to do some serious and lengthy calculations, I'd eventually run out of memory - not so good.Code:class verylongint { .... verylongint &operator+(const verylongint &a) { verylongint *temp = new verylongint; .... // add the contents of "a" and "this" into *temp return *temp; } }; // same example works here...
So what is the "correct" C++ way to solve this type of problem?
[And I'm sorry if this is an FAQ - I couldn't find anything with the search terms I used in the forum search either - but sometimes you only need ONE word cahnged to go from "nothing" to "plenty"]
--
Mats



LinkBack URL
About LinkBacks


