Understanding 'this'.

Jul 13, 2010 at 5:39am
I'm working through the tutorial on this site and I'm a little unsure about this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// this
#include <iostream>
using namespace std;

class CDummy {
  public:
    int isitme (CDummy& param);
};

int CDummy::isitme (CDummy& param)
{
  if (&param == this) return true;
  else return false;
}

int main () {
  CDummy a;
  CDummy* b = &a;
  if ( b->isitme(a) )
    cout << "yes, &a is b";
  return 0;
}


So basically, in this case, this is just a pointer to a CDummy object? And if (&param == this) simply checks if &param is a pointer to a CDummy object?
Jul 13, 2010 at 5:46am
Not just that, it checks to see if param is the same as the object that is calling the function. The class on the left side of the method becomes the "this" pointer inside the method.
Jul 13, 2010 at 6:16am
Uh.. so, if this is in a function call, it would mean a pointer to the object that calls the function? So it's the object calling the function that determines the nature of this?

Or is it the fact that isitme is defined within the CDummy class?
Jul 13, 2010 at 10:32am
istime is an instance method. When the following line is executed this will equal b while inside istime.

b->isitme(a)

Jul 13, 2010 at 1:57pm
More general description

this is passed into all instance methods automatically as the first parameter (hidden in the method declarations).

someVar->someInstanceMethod();

this will equal someVar inside someInstanceMethod

The other type of methods in a class are static "class" methods, these do not have a this pointer, they are not called on an instance of the class, called as someClass::someStaticMethod()
Jul 13, 2010 at 5:35pm
Thanks, I get it now. So 'this' will be a pointer to the object that calls the function.
Jul 13, 2010 at 6:20pm
Exactly
Topic archived. No new replies allowed.