private is non-virtual: Stuck in C++-thinking?

deadalnix deadalnix at gmail.com
Tue Oct 23 12:33:29 PDT 2012


Le 20/10/2012 00:18, foobar a écrit :
> On Friday, 19 October 2012 at 21:09:05 UTC, Nick Sabalausky wrote:
>> My understanding is that this is intentionally disallowed:
>>
>> ---------------------------
>> module foo;
>>
>> class Foo
>> {
>> private void func() {}
>> }
>>
>> class Bar : Foo
>> {
>> // Disallowed:
>> private override void func() {}
>> }
>>
>> void foobar(Foo f)
>> {
>> f.func();
>> }
>> ---------------------------
>>
>> If D had C++'s "private", that restriction would make a lot of sense
>> (except possibly for nested classes, but I dunno). That's because: How
>> can you override a class you can't even access?
>>
>> But D doesn't have a "true" private in the C++ sense. Instead, there
>> is code outside a class which *is* permitted to access "private"
>> members.
>>
>> So am I missing something, or was the sample case above overlooked when
>> making the "private must be non-virtual" decision?
>
> virtual private is an obscure C++ idiom which I think the argument for
> is extremely week. I think Walter made the right decision here in favor
> of more readable code.
>
> I'd do the following:
> ---------------------------
> module foo;
> class Foo {
> private void func() { funcImpl(); }
> protected void funcImpl() {}
> }
>
> class Bar : Foo {
> protected override void funcImpl() {}
> }
>
> void foobar(Foo f) {
> f.func();
> }
> ---------------------------

Being able to define function but prevent from calling them is a very 
usefull thing. Especially when you want to allow to redefine behavior 
that would let the object in an invalid state.


More information about the Digitalmars-d mailing list