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.

0 comments: