Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Member Functions vs Free Functions

I keep on getting confused about this design decision a lot of the time when I'm writing programs, but I'm not 100% sure when I should make a function to be a member function of a class, when to leave it as a normal function in which other source files can call the function when the function declaration is exposed in a header file. Does the desired access to member variables of a class have to do with the decision most of the time?

like image 934
stanigator Avatar asked Jun 08 '09 23:06

stanigator


People also ask

What is the difference between function and member function?

A function declared/defined within a class is a member function and a function declared/defined outside the scope of a class is a function.

What is the difference between member function and non-member function?

A member function is declared in the class but defined outside the class and is called using the object of the class. A non-member function that is declared outside the class but called a normal function inside the main function.

What is member function in C?

Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class.

What are free functions?

The term free function in C++ simply refers to non-member functions. Every function that is not a member function is a free function.


2 Answers

The Interface Principle by Herb Sutter

For a class X, all functions, including free functions, that both
(a) "mention" X, and
(b) are "supplied with" X
are logically part of X, because they form part of the interface of X.

For in depth discussion read Namespaces and the Interface Principle by Herb Sutter.

EDIT
Actually, if you want to understand C++ go and read everything what Herb Sutter has written :)

like image 126
Piotr Dobrogost Avatar answered Sep 28 '22 09:09

Piotr Dobrogost


I use classes when I need to maintain state. If a function doesn't need access to maintained state information, then I prefer a free function because it makes testing and code reuse easier.

If I have a bunch of related functionality but don't need to maintain state, then I prefer putting free functions in a namespace.

like image 38
Ryan Ginstrom Avatar answered Sep 28 '22 11:09

Ryan Ginstrom