Created object on stack and then returned this object to caller. Item deleted but still there??

Discussion in 'C++' started by opistobranchia, Aug 14, 2005.

  1. blah
    F test = getF();
    // Print out shows that an F object was destroyed by the ~F. F set
    var to 0 on delete;
    test.print();
    //reveals that var is still 123
    value is 123 still instead of 0

    F getF()
    {
    F f;
    //default is 0;
    f.setVar(123);
    return f;
    }

    I thought since I created this on the stack instead of the heap that I
    would run into problems. I have not overloaded anything. I thought
    the best way would be to return a pointer to the heap and create the
    object on the heap as well.

    What did I miss, and why does this work? I thought that I had to do
    some overloading to make data copy as well.
    opistobranchia, Aug 14, 2005
    #1
    1. Advertising

  2. Re: Created object on stack and then returned this object to caller.Item deleted but still there??

    opistobranchia wrote:
    > blah
    > F test = getF();
    > // Print out shows that an F object was destroyed by the ~F. F set
    > var to 0 on delete;
    > test.print();
    > //reveals that var is still 123
    > value is 123 still instead of 0
    >
    > F getF()
    > {
    > F f;
    > //default is 0;
    > f.setVar(123);
    > return f;
    > }
    >
    > I thought since I created this on the stack instead of the heap that I
    > would run into problems. I have not overloaded anything. I thought
    > the best way would be to return a pointer to the heap and create the
    > object on the heap as well.
    >
    > What did I miss, and why does this work? I thought that I had to do
    > some overloading to make data copy as well.


    getF() returns an 'F' object, not a ref or pointer to an 'F', but
    a full 'F' object. So, a COPY of the 'F' created inside getF() is
    returned, then 'test' is initialized from that copy. The 'F' created
    inside getF() is destroyed when getF() returns, but the (unnamed)
    copy created from it is returned from getF(), used to init 'test', then
    deleted.

    Larry
    Larry I Smith, Aug 14, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. AAaron123
    Replies:
    2
    Views:
    288
    AAaron123
    Aug 10, 2009
  2. Casey Hawthorne
    Replies:
    3
    Views:
    1,068
    Flash Gordon
    Nov 1, 2009
  3. Chumley the Walrus
    Replies:
    2
    Views:
    242
    Tom Gosselin
    Aug 10, 2004
  4. Replies:
    0
    Views:
    261
  5. Mark
    Replies:
    2
    Views:
    385
Loading...

Share This Page