Search code examples
c++class-method

Why does the "C++ Core Guidelines" recommends the prefer independent functions instead of class members?


The C++ Core Guidelines section C.4 recommends "make a function a member only if it needs direct access to the representation of a class", using the following example:

class Date {
    // ... relatively small interface ...
};

// helper functions:
Date next_weekday(Date);
bool operator==(Date, Date);

I don't understand the reasoning here. In my opinion this would be a better option:

class Date {
    // ... relatively small interface ...

    Date next_weekday(Date const&) const;
    bool operator==(Date const&) const;
};

What is the advantage in this reasoning?


Solution

  • Member functions have access to private members of a class. This means that they can use the internal representation of the class in their logic.

    Non-member functions only have access to public members of a class. This means that they can only use the publicly exposed interface of the class, thus improving encapsulation.