I've read somewhere that the "this" keyword is a default parameter (I suppose it's invisible or something) in any method of a class. Is this true?
"default parameter" is the wrong term. this
can be thought of as an implicit paramter passed to member functions. If there were no member functions then you could emulate them with free functions like this:
struct Foo {
int x = 0;
};
void set_x(Foo* THIS, int x) {
THIS->x = x;
}
However, member functions do exists and the above can be written as:
struct Foo {
int x = 0;
void set_x(int x) {
this->x = x;
}
};
this
is not passed to Foo::set_x
explicitly. Nevertheless, inside the method you can use it to refer to the current object. It can be said to be an implicit parameter to the member function.
However, thats not the whole story. In member functions you actually do not need this
to refer to members of the class. Instead of this->x
just x
would work as well and in contrast to other languages it is common style to ommit the this->
unless necessary. For more details I refer you to https://en.cppreference.com/w/cpp/language/this.
Note that it is not an implicit parameter to all methods of a class. You cannot refer to the current object via this
in a static member function, because there is no "current object" in a static member function.
Also compare to python where self
is explicitly passed:
class Foo:
def __init__(self):
self.x = 0
def set_x(self,x):
self.x = x