C++ Design – Why C++ Complex Functions Are Not Member Functions

cobject-oriented-design

I was looking at the C++ library <complex>, and noticed that functions such as std::conj and std::norm are free functions i.e. static functions not placed inside the std::complex class. Why is this the case?

I would've thought that, from a C++ OOP design perspective, it would've made more sense to have e.g. complex<T> complex<T>::conj() and complex<T> complex<T>::norm() as methods so that I can call auto norm = z.norm() instead of auto norm = std::norm(z).

Am I missing something about how the standard library is designed which justifies why these functions are free?

Best Answer

Am I missing something about how the standard library is designed which justifies why these functions are free?

The C++ standard library does not exclusively follow the OO design paradigm.

Free functions, when combined with parameter overloading, play much nicer when you are writing templated code that should work with both class types and primitive types.

For example, suppose I have a list of values (either complex, as std::complex<float>, or real, as float) and I want to compare them on magnitude. Then I can write a comparison function like

template <class T>
bool magnitude_less(const T& lhs, const T& rhs)
{
  using std::abs;
  return abs(lhs) < abs(rhs);
}

Writing such a function would not be possible if abs for std::complex<T> would have been a member function based on OO design principles.