Shadowing of members
Jonathan M Davis
jmdavisProg at gmx.com
Wed Jan 9 14:22:57 PST 2013
On Wednesday, January 09, 2013 21:36:16 Benjamin Thaut wrote:
> After some refactoring I had a series of bugs that came from renaming
> class members so that the following situation was present.
>
>
> class foo
> {
> float a;
>
> void doSomething()
> {
> float a;
> a = a * 2.0;
> }
> }
>
> The local variable a shadows the member a after the refactoring and
> therefore this code will no longer work as expected. This was quite time
> consuming to track down. So I wanted to ask if we want to prevent that
> with a warning or even an error? D does not allow shadowing of local
> variables, so why is it allowed for members?
Personally, I would find it very annoying to not be able to shadow member
variables, particularly with POD types. Stuff as simple as constructor
parameters would become annoying
struct S
{
this(int i)
{
this.i = i; //this shouldn't produce an error or warning
}
int i;
}
Local variables can't be shadowed by local variables, because there's no way
to access the variable that's been shadowed. That's the only case where
shadowing prevents you from accessing the shadowed variable, and it's the only
case that's currently illegal.
If you want to avoid this sort of problem, then name your member variables
differently (e.g. prepend _ to them). Then it generally doesn't even risk being
an issue except with POD types where you don't make the members private (and
therefore don't prepend _ to them).
- Jonathan M Davis
More information about the Digitalmars-d
mailing list