Package functions cannot be abstract?!

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jan 31 15:49:33 UTC 2019


On Wednesday, January 30, 2019 10:31:45 AM MST Neia Neutuladh via 
Digitalmars-d wrote:
> I didn't realize that C++ allows private virtual functions. With C++, a
> private virtual function is overridable by derived classes, even if they
> aren't friends. This prevents the child classes from calling the function
> despite having defined it. Which is weird.

It does seem weird when you first encounter, it but it's a feature that's
actually quite useful with NVI (Non-Virtual Inheritance). It makes it
possible to override a function's behavior while still guaranteeing that the
function is only called in a certain way. A classic way to use it would be
to have a non-virtual, public function in the base class which runs code
before and/or after calling the private, virtual function. Now, you can do
the same thing without having virtual, private functions. You just can't
prevent anyone from calling the function elsewhere. So, arguably, you can't
prevent a particular class of bugs, but it's probably not something that's a
big deal in practice.

IIRC, TDPL talks about doing NVI in D with interfaces, but whatever it said
exactly doesn't work right now and probably never will.

D's approach of tying whether a function is virtual or not to its access
level prevents certain classes of problems and generally simplifies things,
so it's arguably a win overall, but there's no question that there are some
idioms that it makes impossible. Whether those idioms would be worth
complicating the language in order to have is debatable, but for better or
worse, I would not expect D to change how it handles which functions are
virtual. The main fallout of that is that occasionally, you might have a
function which you have to make public or protected in order to be virtual
when you'd prefer for it to be package or private. The vast majority of the
time, however, it's a non-issue.

- Jonathan M Davis





More information about the Digitalmars-d mailing list