Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member function vs. nonmember function?

Tags:

c++

oop

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?

like image 267
rlbond Avatar asked Apr 03 '09 22:04

rlbond


People also ask

What is member function and non-member function?

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.

What is the difference between function and 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.

When should you define a member function instead of a non-member function?

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.

What is the difference between data member and member function?

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.


1 Answers

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

like image 120
Mark Ransom Avatar answered Sep 21 '22 21:09

Mark Ransom