What is your rule for which functions that operate on a class should be member functions vs. nonmember functions? For example, I have a class which represents a maze using a matrix of bools. I am making a function called isConnected which verifies that 2 points in the maze are in the same region (i.e. it is possible to travel from A to B).
Should this be member or nonmember? What is a good rule?
Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class. You can declare a member function as static ; this is called a static member function. A member function that is not declared as static is called a nonstatic member function.
An ordinary function is nothing but a function with a return type and zero or more arguments. It can be called directly in the main or other functions. A member function is declared or defined within a class or structure. It is generally called with reference to the instance of the class or structure.
But if we get a unified call syntax, the guideline can be the one from C++ Coding Standards: Use a nonmember function if you don't need type conversion in the first argument or don't need access to private data. Use a member function if you do need access to private data.
Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class.
Herb Sutter says "we want to make them nonmember nonfriends if reasonably possible", and he's smarter than I am.
http://www.gotw.ca/gotw/084.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With