I want to give it a shot! :-D
Back in the old days, when there was no "Object Oriented", people used to write functions like this "increaseSalary":
1 2 3 4 5 6 7 8
|
struct Employee { int salary; };
void increaseSalary(Employee* e, int amount)
{ e->salary += amount; }
// give fred a raise.
Employee fred = ...;
increaseSalary(fred, 500);
|
Then some people thought, that actually "increaseSalary" should be directly a part of "Employee", since it always works with the employees. If you somehow attach the "increaseSalary" and all other functions that access the employees salary field directly with the Employee struct, then you can prohibit all *other* functions to access the salary (Nobody likes it, when anyone can freely see your salary, right?).
To explicitly tie the function "increaseSalary" to the struct "Employee", they introduced a new system of calling functions.
1 2 3 4 5 6 7 8 9 10
|
struct Employee
{
int salary;
void increaseSalary(int amount)
{ salary += amount; }
}
// give fred a raise.
Employee fred = ...;
fred.increaseSalary(500);
|
Noticed how the first parameter moved in front of the function call? You are probably already known to this kind of calling a function.
As the function "increaseSalary" is now directly coupled with the employee structure, you don't need to pass the employee as parameter anymore. All members of the employee are directly "merged" into your current scope.
However, sometimes you still *have* to access the old "first parameter" thing, for example if you want to forward call to another function that still takes a first-parameter (because, say, it's not so close coupled with Employees). Lets assume you have a HumanResource department that needs to get informed of the new salary. The department provides a function to inform of the raise, which you have to call.
1 2 3
|
// That's how to inform the HR about the new salary.
void informAboutRaise(Employee* employee);
...
|
that's how it would look like if there were no classes and structs (the old way)
1 2 3 4 5
|
void increaseSalary(Employee* e, int amount)
{
e->salary += amount;
informAboutRaise( e ); // pass the employee to the HR department
}
|
and that's how it looks now. Spot the usage of "this"?
1 2 3 4 5 6 7 8 9
|
struct Employee
{
int salary;
void increaseSalary(int amount)
{
salary += amount;
informAboutRaise( this ); // <-- Here you need to pass the former "first parameter", which is this.
}
}
|
"this" basically is the pointer to the struct itself which was used before the . when called to the member function.
Ciao, Imi.
PS: Writing "this->" is the way of explicitly saying, that you mean the variable from the enclosing struct.
Line 6 in my last code block example could also be written as
Both ways are the same, but some people prefere "this->salary" as it makes it crystal clear what "salary" you are talking about.