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?
CodePudding user response:
"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.
Note that it is not an implicit parameter to any method 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
CodePudding user response:
You can think of it that way; i.e. when you make a method call
myObject.Foo(1, 2, 3);
and the method Foo(int a, int b, int c) executes, the code within the method has access to parameters a, b, and c, and also access to the pointer this:
void MyObjectClass :: Foo(int a, int b, int c)
{
printf("a=%i b=%i c=%i this=%p\n", a, b, c, this);
}
... this isn't explicitly listed in the arguments list but it's passed as part of the method-call (since without it, Foo wouldn't have access to any of its own member-variables, which would be a problem for most methods)
