3 ms·
This idea _almost_ sounds like a joke. A member function is indeed different from a non-member function precisely because it is not a member of the set of func
by verytrivial 12y ago
This idea _almost_ sounds like a joke. A member function is indeed different from a non-member function precisely because it is not a member of the set of functions responsible for maintaining the object's invariants. Treating
f(x, y);
as
x.f(y);
only makes sense (to me?) if all other things being equal, if f(x, y) is a friend of the class. And picking the member function form over the non-member function in the caller's scopes seems like a step away from encapsulation. Prefer non-member functions. Scott says so!
- vidarh 12y agoConsider that under the hood, they result in the same code (unless f is a virtual member function, in case it'd be equal to x.<vtable ptr>[vtable offset of f](x,y)). For non-virtual member functions they differ in syntax and lookup, not implementation. In effect they provide two different syntaxes for something that is _very_ often the same thing, namely executing a piece of code that logically "belongs" to and operates on the first argument. E.g. look at the C standard library, and consider how many of the functions there operates on the state of the first argument. This change would let you write an f() that does not have access to the internals of x, yet can still be called the same way as the member functions, providing increased uniformity and making the choice of member function vs. non-member function more of an implementation choice by letting you reduce the impact on the documented API: > And picking the member function form over the non-member function in the caller's scopes seems like a step away from encapsulation. Prefer non-member functions. Scott says so! Preferring non-member functions is exactly why I think this seems interesting. The awkwardness of splitting an interface so people have to remember what is a member function and what is a non-member function, and having to decide how it should be split, easily results in a lot of stuff ending up as member functions when it doesn't have to be. If it's transparent to the user, there are fewer reasons to prefer member functions, not least because "promoting" a non-member function to a member function if you later need access to more internal state becomes easier.
- saucetenuto 12y agoI don't agree. The _signature_ should indicate whether a function has access to a class's internals or not, but the caller shouldn't have to care. This is already true in C++ today: when we write f(x), f might be a normal free function or it might be a friend of x. Viewed from that angle, this proposal makes C++ more consistent, not less: it breaks a needless dependency between syntax and semantics.