0

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?

André Wagner
  • 1,330
  • 15
  • 26
  • 3
    *Why* do you think member functions would be a better option? :) – Quentin May 11 '17 at 13:07
  • 1
    I'm with you on this, subject to making the "helper functions" `static`. – Bathsheba May 11 '17 at 13:07
  • 1
    Look at [how-non-member-functions-improve-encapsulation](http://stackoverflow.com/questions/1692084/how-non-member-functions-improve-encapsulation) – Jarod42 May 11 '17 at 13:10
  • Your'e aware of the C++ code philosophy of "don't pay for what you don't use", I hope. It can be said that breaking encapsulation incurs a price. So this guideline just applies the same philosophy to the price of breaking encapsulation. – StoryTeller - Unslander Monica May 11 '17 at 13:16
  • Even though this is a dup, I disagree with the downvoting. Going from Core Guidelines to something written by Scott Meyer is non-trivial. Also, the other question knows this is about encapsulation. Finally, the CG specifies independent and the other post is about non-member. In short, finding the dup is non-trivial for most people. – Roy Falk Sep 27 '19 at 08:28

2 Answers2

3

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.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
0

It increases encapsulation

When you change the private implementation of Date, you only have to check // ... relatively small interface ... for places where previous assumptions may no longer hold, instead of // ... relatively small interface ... + next_weekday + operator== + ...

Caleth
  • 52,200
  • 2
  • 44
  • 75