Name resolution (programming languages): Difference between revisions

Content deleted Content added
4-space indention for Java
dedent code examples
Line 41:
For example, the parameter "foo" shadows the local variable "foo" in this common pattern:
<source lang="java">
private int foo; // Name "foo" is declared in the outer scope
 
public void setFoo(int foo) { // Name "foo" is declared in the inner scope, and is function-local.
this.foo = foo; // Since "foo" will be first found (and resolved) in the ''innermost'' scope,
// in order to successfully overwrite the stored value of the attribute "foo"
// with the new value of the incoming parameter "foo", a distinction is made
// between "this.foo" (the object attribute) and "foo" (the function parameter).
}
}
 
public int getFoo() {
return foo;
}
}
</source>
Name masking can cause [[Function overloading#Complications|complications in function overloading]], due to overloading not happening across scopes in some languages, notably C++, thus requiring all overloaded functions to be redeclared or explicitly imported into a given namespace.
Line 62:
For example, in this code:
<source lang="cpp">
class Point {
private:
double x, y;
public:
Point(double x, double y) { // x and y declared here mask the privates
setX(x);
setY(y);
}
 
public:
void setX(double newx) { x = newx; }
Point(double x, void setY(double newyy) { // x and y =declared here mask newy;the }privates
setX(x);
setY(y);
}
 
void setX(double newx) { x = newx; }
void setY(double newy) { y = newy; }
}
</source>
within the <tt>Point</tt> constructor, the class variables <tt>x</tt> and <tt>y</tt> are [[Variable shadowing|shadowed]] by local variables of the same name. This might be alpha-renamed to:
<source lang="cpp">
class Point {
private:
double x, y;
 
public:
Point(double a, double b) {
setX(a);
setY(b);
}
 
void setX(double newx) { x = newx; }
void setY(double newy) { y = newy; }
}
 
void setX(double newx) { x = newx; }
void setY(double newy) { y = newy; }
}
</source>
In the new version, there is no masking, so it is immediately obvious which uses correspond to which declarations.