Thursday, September 22, 2011

C++ part 2 returning an object

The following code in C++ is not the same.

Fraction multiply(Fraction * f2) {
        return Fraction (m_Numer*f2->m_Numer, m_Denom*f2->m_Denom);
    Fraction multiply1(Fraction * f2) {
        Fraction a(m_Numer*f2->m_Numer, m_Denom*f2->m_Denom);
        return a;

The first one return an actual object. And second is returning a local object which will be invalid after the method returns. Therefore the second method call will cause run-time error.

1 comment:

smstester said...

not true. local object 'a' will be pushed to the stack (a copy will be made), and valid object will be returned. Just like it was an int.

You would get runtime error if you returned a pointer (or reference) to the local object.