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.
Am I the only one who noticed a void return type returning a value?
void CalculateDifference( int nNumber ) { return minus( nNumber ); }
🙂
Thanks AJ for catching my bad return statement. I have now fixed it.
I’m just busting your chops! 🙂
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.
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.