Why private methods cant be virtual?
er.krali at gmail.com
Tue Sep 22 14:11:14 UTC 2020
On 22/9/20 15:04, claptrap wrote:
> The thread title is...
> "Why private methods cant be virtual?"
> IE Not...
> "how do I override private functions in a non-polymorphic manner."
> And what you suggest wont work because I was asking about virtual
> functions, so I specifically want polymorphism. And FWIW it's no big
> deal I can just use protected, i wasn't looking for a solution, I was
> looking for an explanation as to why it was done that way. But
> apparently there is none.
TL;DR: Wouldn't `package`  visibility probably be a better option in
My guess is that this was taken from Java, as in fact most of the D
class system seems to be (see `synchronized`, reference semantics, etc).
There it makes sense, because there is only one class per compilation
unit, so the `private` members are in effect hidden from any child
classes and it wouldn't make sense to override them.
The different (and to me still confusing, but I understand the reasoning
behind it) factor in D is that the encapsulation unit is the module, not
the class. Hence, you can have multiple classes in the same module
inheriting from each other.
These classes can then access the private members of the parent, but not
override it, which as you say is somewhat strange.
I personally would rather have the class as the encapsulation unit for
classes, and then this point would be moot, but I come mostly from Java,
so that might just be my bias, and, as I said, I understand there are
also good reasons to keeps the module as the common encapsulation unit.
Still, I think that when you design a class, if you declare something as
`private` means that it's an internal implementation detail that you
don't want to expose, much less any child class to override.
In fact, to allow only the classes in the same module to override a
private method looks to me like code smell. You likely have good reasons
to do it, but, even if it were possible, I would probably try to do it
in a way where the intent is clearer, either through `protected` or
`package` visibility... the latter has the added benefit that you can
split the module later if needed.
More information about the Digitalmars-d-learn