I'm wondering what kind of class member access friend
functions and static
member functions have for class objects. Specifically, what the differences are and why to use one over the other. It's my understanding that functions declared as friend
of a class or as static
members both have access to private members of any instance of that class.
I'll give a quick example to show why they seem so similar to me. Both functions operator<
and MyClass::lessThan
seem to have the same access privileges and can do the exact same thing.
class MyClass {
friend bool operator<(const MyClass &left, const MyClass &right);
public:
MyClass(int pub, int priv) : m_pub(pub), m_priv(priv) {}
static bool lessThan(const MyClass &left, const MyClass &right);
int m_pub;
private:
int m_priv;
};
bool operator<(const MyClass &left, const MyClass &right) {
return ( (left.m_pub < right.m_pub) && (left.m_priv < right.m_priv) );
}
bool MyClass::lessThan(const MyClass &left, const MyClass &right) {
return ( (left.m_pub < right.m_pub) && (left.m_priv < right.m_priv) );
}
int main(int argc, const char* argv[]) {
MyClass a(1, 2),
b(3, 4),
c(-1, 1);
cout << "a < b = " << (a<b) << endl;
cout << "a lessThan b = " << MyClass::lessThan(a,b) << endl;
cout << "a < c = " << (a<c) << endl;
cout << "a lessThan c = " << MyClass::lessThan(a,c) << endl;
}
Clearly this is a simplified example, but I suppose my question is two-part:
- What are the differences between friend and static functions in regards to member access?
- What kinds of things should come into consideration when deciding which to use?