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.

Wednesday, September 21, 2011


After spending so many years programming in C#, I really appreciate how life make it so simple by language designers. Consider the following code written in c++:

Fraction a = b;


Fraction a;

In C#, these 2 blocks of code are saying the same thing. It declares a variable and assigns it value b (i.e. a and b now pointing to the same object).

However, in C++, it is totally different. The first code block is to create an object of class Fraction by calling constructor(const & Fraction). The second block is to create an object with default constructor, and call the operator=(const Franction &). Depends on how you write your member functions of the class, the code might or might not work the way it looks.

I like C#'s version, since the code worked exactly it is read. Whereas, in C++, errors might be introduced.