I'm learning several languages. 5 at once but I took a liking to one specific feature of java. The This keyword.
From their tutorial:
/*Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this*/
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
//but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Why can't we do this in C++? The compiler says it's ambiguous or that the parameter x shadows a member of such and such class.
Is there any tricks to doing this?
Also another thing I'd like to know:
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
In the above, they use the this keyword to call another constructor of the exact same class! I read somewhere that it's bad to do this in c++ and that it's better to make a new object and just assign it to the current one. Is this true or can I actually do this in C++?