3 Years
Discussion Span
Last Post by rubberman

I am amazed that people don’t even try to Google for an answer. Most of the time the first page has the answer and so much more.


In truth, the return value of a constructor is the object itself, or a temporary reference to an object that will soon disappear. Whether it is assigned to a variable, or a copy (via reference) is, depends upon whether or not it is used in the declaration of the variable, or in a simple assignment operator. Here is an example:

class foo
    int m_bar;
    foo(int aBar = 0 ) : m_bar(aBar) {}

int main(void)  // I seem to use this pattern a lot! :-)
    foo aFoo0;      // Constructed with default value of 0, m_bar == 0
    foo aFoo1(1);   // Constructs foo with m_bar == 1
    foo aFoo2 = 2;  // Operates like the previous, but m_bar == 2
    foo aFoo3 = foo(3); // Copies foo(3) to aFoo3, treating foo(3) as a reference, m_bar == 3
    foo& aFooRef = aFoo3;   // A reference to aFoo3, m_bar == 3

    // Now, assignment from a temporary reference
    aFoo0 = foo(4);     // aFoo0.m_bar now == 4 since foo(4) (as a reference) was copied to aFoo0.
    aFoo0 = aFooRef;    // aFoo0.m_bar now == 3 since aFoo3 is now copied to aFoo0.
    return 0;

I'm sure you are confused now, right! :-)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.