Thread: returning a temporary class object

  1. #1
    samurai warrior nextus's Avatar
    Join Date
    Nov 2001
    Posts
    196

    Question returning a temporary class object

    i have a class that returns a temporary object when i overload the addition operator
    here is the sample code

    Code:
    CBox operator+(const CBox& aBox) // CBox is a class
    {
       float h = this->m_height + aBox.m_height;
       float b = this->m_breadth + aBox.m_breath;
       float l = this->m_length + aBox.m_length;
    
       return CBox(h, b, l);
       // returning a temporary CBox object
    }
    help is appreciated...thanks...this is always puzzles me because i thought objects cease to exist after they go out of scope...

  2. #2
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    It's not going out of scope. You'll be invoking some form of copy constructor in the calling expression (or your compiler may perform a return value optimsation).

    If you were returning a reference to your local object your assumption would be correct and I believe the outcome would be undefined.
    Joe

  3. #3
    samurai warrior nextus's Avatar
    Join Date
    Nov 2001
    Posts
    196
    what is a return value optimization?

  4. #4
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    The compiler may notice that you're constructing an object within a function in order to return it. Instead of constructing a local object and then calling a copy constructor / assignment operator when the object is returned it'll construct / assign to the object that accepts the return value. Something like -

    object a = b + c

    Instead of constructing a temporary value within operator+ to store the result of the addition, and using this an argument in 'a's copy constructor 'a' will be constructed from within operator+ as if it had been passed in by reference as a hidden argument.

    This kind of thing may be necessary if you're calling operator+ allot; as multiple unnecessary construction may hurt performance (if this is a consideration). But presently not all C++ compilers carry it out effectively.
    Joe

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 05:01 PM
  2. linker error
    By tasha302 in forum C++ Programming
    Replies: 3
    Last Post: 12-14-2006, 12:00 AM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 04:33 PM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM