Lets write a struct and a standalone function:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
struct List {
Node* tail;
int count;
};
void push_back( List* list, int data ) {
// code ...
list->tail->data = data;
list->tail->next = node;
list->tail = node;
list->count++;
}
|
and use them:
1 2 3 4
|
int main {
List one;
push_back( &one, 42 );
}
|
Then change the standalone function into a member:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
struct List {
Node* tail;
int count;
void push_back( int data );
};
void List::push_back( int data ) {
// code ...
this->tail->data = data;
this->tail->next = node;
this->tail = node;
this->count++;
}
|
and use:
1 2 3 4
|
int main {
List one;
one.push_back( 42 ); // during this function call the 'this' points to one
}
|
Do you notice similarities and differences?
The
this
is a pointer that points to the object, whose member was called.
The
this
is automatically created and set for each member function.
You do need to use the this, if there is name ambiguity.
1 2 3 4 5 6
|
struct Example {
int data;
bool test( int data ) {
return this->data == data;
}
};
|
The function wants to use both the member 'data' of Example and the function parameter 'data'. Inside the function the parameter name hides (masks) the member that has same name, but with
this
we can differentiate them. (It would be easier to choose names differently here, but not always.)
Your professor's code is unlikely to have name masking. She probably wants to emphasize that tail and nodeCount are member variables of the class. The code is bit more verbose, but also more explicit and self-documenting. That is a style choice. Optional.