Thread overview | |||||
---|---|---|---|---|---|
|
March 13, 2019 Is this a DMD bug, or correct behavior? | ||||
---|---|---|---|---|
| ||||
Well, a snippet is worth a thousand words: https://run.dlang.io/is/hjvMDO I came across this strange behavior, however I am unsure as to whether this is correct behavior, or just an expected behavior of shadowing. It seems like there should at least be some sort of compiler error/warning for this. |
March 13, 2019 Re: Is this a DMD bug, or correct behavior? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Foo Bar | On Wednesday, 13 March 2019 at 00:27:02 UTC, Foo Bar wrote:
> I came across this strange behavior, however I am unsure as to whether this is correct behavior, or just an expected behavior of shadowing.
Yes, it is correct behavior, though it does trip a lot of people up.
Each variable set in a class declaration is independent. Lookups go for the first one they see up a chain from the static type.
Inside the override foo, it looks up and sees B.boolean. But outside, you cased to A, so it can only see A.boolean.
Object-oriented pattern here is typically to keep your member vars private and read/write through accessor methods instead, which can be virtual and thus be overridden in child classes as needed.
|
March 13, 2019 Re: Is this a DMD bug, or correct behavior? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | On Wednesday, 13 March 2019 at 00:50:35 UTC, Adam D. Ruppe wrote:
> On Wednesday, 13 March 2019 at 00:27:02 UTC, Foo Bar wrote:
>> I came across this strange behavior, however I am unsure as to whether this is correct behavior, or just an expected behavior of shadowing.
>
> Yes, it is correct behavior, though it does trip a lot of people up.
>
> Each variable set in a class declaration is independent. Lookups go for the first one they see up a chain from the static type.
>
> Inside the override foo, it looks up and sees B.boolean. But outside, you cased to A, so it can only see A.boolean.
>
> Object-oriented pattern here is typically to keep your member vars private and read/write through accessor methods instead, which can be virtual and thus be overridden in child classes as needed.
Ah, okay. Thanks for the clarification.
|
Copyright © 1999-2021 by the D Language Foundation