"this" pointer points to the object for which the member function is
called. My question is :
When we must use a "this" pointer? any examples? thanks
I offered the following example in response to a similar question a
bit ago.
Suppose you have a class called Thing, which includes two pointer
members called next and previous. Suppose you have a function tieup,
which ties up two Things in the sense that the first one's "next"
pointer points to the second Thing, and the second ones "previous"
pointer points to the first Thing. We can do this as follows:
void tieup(Thing *first, Thing *second) {
first -> next = second;
second -> previous = first;
return;
}
However, this means an external function - tieup - has to be able to
mess about with the internal variables of a Thing. Suppose your boss
does not like this - he thinks Things should be "encapsulated" and
that this sort of thing should be handled by a member function. So you
make one as follows:
void Thing::tieupwith(Thing *nextone) {
next = nextone;
nextone -> previous = this;
return;
}
And, unless I've made an error,
first -> tieupwith(second);
should have the same effect as
tieup(first, second);
Does that help?
Paul.