Why private methods cant be virtual?
clap at trap.com
Tue Sep 22 21:16:21 UTC 2020
On Tuesday, 22 September 2020 at 13:19:10 UTC, Daniel Kozak wrote:
> On Tue, Sep 22, 2020 at 3:05 PM claptrap via
> Digitalmars-d-learn < digitalmars-d-learn at puremagic.com> wrote:
>> The thread title is...
>> "Why private methods cant be virtual?"
>> IE Not...
>> "how do I override private functions in a non-polymorphic
>> 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.
> And I did not try to show solution. It was just an answer to
> this part of your response:
> So final private functions can be overriden? It seems not, but
> the sentence is definitely confusing if not just plain wrong.
> So the reason why there is this:
> "Functions marked as final may not be overridden in a derived
> class, unless they are also private"
> Is because with private methods final keyword has no meaning.
Its not that final has no meaning for private methods, but that
final has no meaning for non-virtual methods, and private methods
happen to be non-virtual. IE. It's a side effect of making
private methods non-virtual, not a direct effect of them being
And lets be honest, overriding a virtual method is a different
thing to "overriding" or rather hiding a non virtual one.
It's mistake to use the same terminology for both cases.
> And there is a reason "Why private methods cant be virtual?".
> It is because it would break existing code.
Why would it break existing code?
> And because private methods are final it makes them fast.
> And yes compiler probably could findout that method could be
> made non-virtual but I am not sure how easy is this and how it
> would slow down compilation times
Testing it out on compiler explorer it seems neither LDC or DMD
de-virtualize a simple case, a class with one method, no decedent
So maybe the docs shouldn't say that it does so.
More information about the Digitalmars-d-learn