The this pointer

Sep 26, 2009 at 12:53am
Does anyone know what the this pointer is used for in C++? I'm learning about it but I can't seem to find a true purpose to it. I'd imagine I would just call member variables instead of go to the trouble of learning a whole 'nother method of pointers.
Sep 26, 2009 at 12:57am
It allows you to explicitly access the current class. It can be used to avoid naming conflicts between say, a global variable and a member variable. It can also be used just for clarity to show that you are accessing members, but in most cases it is not necessary.
Sep 26, 2009 at 1:59am
In many cases, though, it is necessary, especially when dealing with templated classes.


C++ class functions are a kind of fancy trick. The idea is to combine state (data) with transitions (functions). You can do that in C easily enough:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct Employee_t
  {
  char firstname[ 50 ];
  char surname[ 50 ];
  unsigned id;
  double salary;
  };

void Employee_initialize( struct Employee_t* this )
  {
  *this->firstname = '\0';
  *this->surname = '\0';
  this->id = 0;
  this->salary = 0.0;
  }

void Employee_read_from_file( struct Employee_t* this, FILE* f )
  {
  fgets( this->firstname, sizeof( Employee_t::firstname ), f );
  ...
  }
...

struct Employee_t employee;
Employee_initialize( &employee );
Employee_read_from_file( &employee, stdin );
...

C++ just makes this much more convenient:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct Employee_t
  {
  string firstname;
  string surname;
  unsigned id;
  dobule salary;

  Employee_t():
    firstname( "" ),
    surname( "" ),
    id( 0 ),
    salary( 0.0 )
    { }

  read_from_file( istream& ins )
    {
    getline( ins, firstname );
    ...
    }
  };
...

Employee_t employee;
employee.read_from_file( cin );

Hope this helps.
Topic archived. No new replies allowed.