Re: Function Returning a local object???

From: Rich Herrick (rich.delete.me_at_richherrick.com.delete.me.too)
Date: 09/06/04


Date: Mon, 06 Sep 2004 00:37:20 GMT


"Olumide" <50295@web.de> wrote in message
news:c837e7e8.0409051616.2d642d3e@posting.google.com...
> I'm studying Nigel Chapman's Late Night Guide to C++ which I think is
> an absolutely fantastic book; however on page 175 (topic: operator
> overlaoding), there the following code snippet:
>
> inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global
> function
> {
> MFVec res = z1;
> res += z2
> return res; // WHY???
> }
>
> MFVec is the (vector) class:
>
> class MFVec {
> public:
> MFVec(float x, float y);
> // other member functions
> private:
> float xcoord, ycoord;
> }
>
> My problem however lies with the line 3 of the global operator+()
> function because it returns the local variable res, which I assume is
> destroyed as soon as the function is exited. This resembles a dangling
> refrence and I don't know why its not illegal. Anyone knows why?
>
> I don't mind thorough answers; in fact I kidda prefer them ;-)
>
> Thanks
>
> - Olumide

The code is fine. It is not returning the local, but a copy. The return
type is the class, not a reference.



Relevant Pages

  • Re: hexadecimal to float conversion
    ... > floating point. ... > number and would like to convert it into float. ... If you are trying to avoid scanf() have a look ... If you are trying to move in the opposite direction from the code snippet ...
    (comp.lang.c)
  • Re: function use error...?
    ... > can anyone tell me how to correct the error in this code snippet:? ... > void begin; ... > void compute_x(float a, float b, float c) ... You should use a loop, instead of using recursion to loop. ...
    (comp.lang.cpp)
  • Re: Why isnt my compiler warning me about this?
    ... > In the following code snippet, I declare the variable val as float in ... > the calc.h header file, ... I get no errors about the difference between float and int. ...
    (comp.lang.c)
  • Re: 1.090516455488E9 / 1000000.000 ???
    ... I got a simple and probably stupid newby question.. ... Code snippet? ... Print does seem to round at 12 digits. ... I know something with float and //... ...
    (comp.lang.python)