fotinsky
fotinsky

Reputation: 992

Where/How to declare and implement help-function which has to be used by member method?

I implemented a public member method in a class, which uses std::sort(). The function sort on the other hand takes a compare function (let's call it helpSort() ) as third argument.

Now the question is, where or how do I have to declare and implement helpSort() so that:

  1. it will work.
  2. encapsulation is ensured.

What is considered here as good design?

Declaring it plain inside the class does not work.

Upvotes: 0

Views: 88

Answers (2)

NicholasM
NicholasM

Reputation: 4673

I think the best solution would be to implement

bool helpSort(const T& a, const T& b)

as a free function, and sort objects based on their publicly observable properties. If there are const accessor member functions you need to add, and they make sense as part of the observable properties of the class, you could add those member functions in order to accomplish this.

As an example, if you could implement your sort function as

bool helpSort(const T& a, const T& b) { return a.property() < b.property(); }

where property() is a public function, this will make the helpSort function work, even as the implementation of T changes, as long as the public interface/contract for class T remains the same. That is, your helpSort function will continue to compile and remain meaningful, as long as the meaning of property() is not changed, even as your implementation of class T evolves.

If the number of accessors you would need becomes unreasonable, I think it's reasonable to declare helpSort a friend function. I personally think friend functions taking const instances as parameters are much less dangerous than friend class cases (which I avoid at all costs). In principle, such a function could be implemented in terms of public accessors, but perhaps it would be inconvenient or unreasonable.

If you have heard advice to "never have friends", it's possible someone had bad experiences with friend classes, which really can rupture encapsulation.

Finally, you can declare a static member function within your class as a comparison function. I think it's pretty similar to a friend free function. The one advantage to a free function is that you know, structurally, that it cannot alter the state of the object by modifying some static variable within the class.

You can read more about the differences at these links:

Static member functions

What kind of member access do friend and static member functions have?

Upvotes: 1

Tristan Brindle
Tristan Brindle

Reputation: 16824

Declaring it plain inside the class does not work.

Why not? You can write helpSort() as a static private member function and pass that as the comparator and it should work just fine. Without knowing more about what you're trying to do, that would be my preferred solution.

Upvotes: 1

Related Questions