private method in interface

Jonathan M Davis jmdavisProg at gmx.com
Fri Jun 3 13:02:53 PDT 2011


On 2011-06-03 11:59, Michael Shulman wrote:
> On Fri, Jun 3, 2011 at 11:22 AM, Jonathan M Davis <jmdavisProg at gmx.com> 
wrote:
> >> However, given that in D, 'private' only means restricted to a
> >> *module*, it's less clear to me why private functions should be
> >> singled out as non-virtual. I might want certain methods to be
> >> accessible only within a given module, but still allow them to be
> >> overridden within a class hierarchy that exists entirely inside that
> >> module. Unless the point of view is that each class should always
> >> exist in its own module?
> > 
> > No, there would be nothing wrong with overriding private member functions
> > within a module with derived classes (assuming that private were
> > overridable).
> 
> Okay.  Then I don't quite understand the rationale for all private
> functions being non-virtual.

Efficiency. Virtual calls cost more than non-virtual calls. And if you're 
never going to override a function, why have it be virtual and incur that 
extra cost? C++ defaults to non-virtual and has the virtual modifier for 
making functions virtual, which gives you the efficiency by default with the 
flexibility to make them virtual if you want to. The problem is that it's 
still possible to override non-virtual functions, which is almost always a 
bug. Java took the route of making all functions virtual except where the 
compiler optimizes them to be non-virtual. D did the same except for private 
functions, likely on the theory that you basically never override private 
functions, so why incur the cost? And if you don't know about NVI, having a 
virtual private function is just plain weird. Lots of people are surprised to 
find out that it's legal to override private functions like that in C++.

So, in most cases, you don't want virtual private functions. The 
overridability is generally useless and it costs more to call them. Worse, 
they can't be inlined, because the call is polymorphic and you don't know 
whether the version of the function in the current class or one in a derived 
class will be called. The one exception as far as usefulness goes is the NVI 
idiom, and TDPL said that you could do it (I think because Andrei didn't 
realize that you couldn't rather than because it was intended to be changed in 
the language). However, you can still effectively do NVI with protected 
functions, so arguably, the costs to making private functions virtual far 
outweigh the benefits. But the fact that TDPL says that private is overridable 
for NVI may make it so that the language is changed to allow it. We'll have to 
see.

In any case, the reason that you don't normally want private functions to be 
virtual is because virtual functions cannot generally be inlined and are less 
efficient than non-virtual functions.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list