Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do generic programming designs prefer free functions over member functions?

I recently got introduced the design of generic programming libraries like STL, boost::graph, boost PropertyMaps http://www.boost.org/doc/libs/1_54_0/libs/property_map/doc/property_map.html

What is the rationale behind using free functions like get(PropertyMap, key) over member functions like PropertyMap.get(key)?

I understand that the most generic form of these functions are defined in the "boost" namespace. Suppose I define a new PropertyMap in my namespace "project", what is the best place to define it's corresponding "get" function? "boost" or "project"

like image 560
Vikas Avatar asked Dec 07 '22 06:12

Vikas


1 Answers

There are two different reasons:

  • Better Encapsulation: by minimizing the number of functions having access to the class attributes, you improve encapsulation.

  • Extensibility: in C++, a namespace definition is open (you can add to it) whilst a class definition is closed; therefore you can add free functions, but not member functions.

While encapsulation is more a matter of taste, extensibility is extremely important in generic programming. You do not want to have to abandon a 3rd party type just because it lacks the one method you need... and of course some types (such as the built-in types or standard library types) cannot be extended at all.

like image 136
Matthieu M. Avatar answered Feb 07 '23 00:02

Matthieu M.