Contents Up << >>

Should my class declare a member function or a friend function?

Use a member when you can, and a friend when you have to.

Sometimes friends are syntactically better (e.g., in class "Fred", friend fns allow the "Fred" param to be second, while members require it to be first). Another good use of friend functions are the binary infix arithmetic operators (e.g., "aComplex + aComplex" probably should be defined as a friend rather than a member, since you want to allow "aFloat + aComplex" as well; recall members don't allow promotion of the left hand arg, since that would change the class of the object that is the recipient of the member function invocation).

In other cases, choose a member function over a friend function.

  • Input/output via <iostream.h> and <stdio.h>