Non-member non-friend functions vs private functions

28 June, 2009 § 5 Comments

Herb Sutter has said that the most object oriented way to write methods in C++ is using non-member non-friend functions. Should that mean that I should take private methods and turn them into non-member non-friend functions? Any member variables that these methods may need can be passed in as parameters.

Example (before):

class Number {
 public:
  Number( int nNumber ) : m_nNumber( nNumber ) {}
  int CalculateDifference( int nNumber ) { return minus( nNumber ); }
 private:
  int minus( int nNumber ) { return m_nNumber - nNumber; }
  int m_nNumber;
};

Example (after):

int minus( int nLhsNumber, int nRhsNumber ) { return nLhsNumber - nRhsNumber; }
class Number {
 public:
  Number( int nNumber ) : m_nNumber( nNumber ) {}
  int CalculateDifference( int nNumber ) { return minus( nNumber ); }
 private:
  int m_nNumber;
};

Am I on the right track? Should all private methods be moved to non-member non-friend functions? What should be rules that would tell you otherwise?

I’ve asked the question on Stack Overflow. Feel free to leave a response there so I can better track responses and award credit.

Tagged: , ,

§ 5 Responses to Non-member non-friend functions vs private functions

  • A.J. says:

    Am I the only one who noticed a void return type returning a value?
    void CalculateDifference( int nNumber ) { return minus( nNumber ); }🙂

  • msujaws says:

    Thanks AJ for catching my bad return statement. I have now fixed it.

  • A.J. says:

    I’m just busting your chops!🙂

  • A.J. says:

    Non-member non-friend functions includes static functions too right? I bet making the “minus” function a static function should also be acceptable. And you could still keep it private/protected.

  • msujaws says:

    Non-member non-friend functions *don’t* include static functions. A static function is still within the class namespace and has access to any static member variables.

    The goal of writing non-member non-friend functions is to make it explicitly known what side-effects a function call may have. If there are no global variables (and no free static variables within the said function), then a non-member non-friend function should have no state to it.

    The removal of state from a method like this will allow you to achieve better object oriented code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Non-member non-friend functions vs private functions at JAWS.

meta