non virtual interfaces

Jonathan M Davis jmdavisProg at gmx.com
Fri Sep 20 09:09:49 PDT 2013


On Friday, September 20, 2013 22:40:48 Alexandr Druzhinin wrote:
> 20.09.2013 12:45, Ali Çehreli пишет:
> > On 09/19/2013 10:31 PM, Alexandr Druzhinin wrote:
> >  > if I use protected instead of private in interface like:
> > private member functions are non-virtual.
> 
> But I just use code example from TDPL russian edition. And TDPL says
> clearly that (un)transmogrify() are private and CardboardBox _maynot_
> make (un)transmogrify() non-private - this is highlighted as compiler
> support of NVI idiom. Is it wrong example, I guess?

TDPL is mostly correct but not completely correct. AFAIK, it has never been 
implemented that you can override private functions in interfaces like TDPL 
describes. With classes, package and private are _never_ virtual, so private 
will have be treated differently interfaces in order to do what TDPL describes. 
That may or may not be implemented in the future.

You can use NVI with classes just fine just so long as you use protected rather 
than private, but making it private there won't work either, because private 
is never virtual (and it wouldn't really help you any if it were, because 
while the base class private function might not be callable, the derived class 
one would still be callable by the derived class, so trying to prevent the 
virtual function in NVI from ever being called outside of the base class is 
broken in the first place - including in C++ where it was originally devised). 
What NVI helps with is making it so that the public function being called as 
part of the API is non-virtual, allowing you to do stuff before and after the 
hidden virtual function being called, but the derived classes can still call 
their implementation of the hidden, virtual function.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list