Choosing between instance methods and separate functions?

Posted by StackedCrooked on Stack Overflow See other posts from Stack Overflow or by StackedCrooked
Published on 2010-04-06T18:15:04Z Indexed on 2010/04/06 18:33 UTC
Read the original article Hit count: 278

Filed under:
|

Adding functionality to a class can be done by adding a method or by defining a function that takes an object as its first parameter. Most programmers that I know would choose for the solution of adding a instance method.

However, I sometimes prefer to create a separate function. For example, in the example code below Area and Diagonal are defined as separate functions instead of methods. I find it better this way because I think these functions provide enhancements rather than core functionality.

Is this considered a good/bad practice? If the answer is "it depends", then what are the rules for deciding between adding method or defining a separate function?

class Rect
{
public:
    Rect(int x, int y, int w, int h) :
        mX(x), mY(y), mWidth(w), mHeight(h)
    {
    }

    int x() const { return mX; }

    int y() const { return mY; }

    int width() const { return mWidth; }

    int height() const { return mHeight; }

private:
    int mX, mY, mWidth, mHeight;
};


int Area(const Rect & inRect)
{
    return inRect.width() * inRect.height();
}


float Diagonal(const Rect & inRect)
{
    return std::sqrt(std::pow(static_cast<float>(inRect.width()), 2) + std::pow(static_cast<float>(inRect.height()), 2));
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about best-practices