This pointer

hi,
I having trouble with the this pointer what exactly is it used for? Is it used only for argments with same method member names like this code?
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//File example of classes (to benefit from the this pointer =D
#include <string>
#include <iostream>
using namespace std;

//declare class dog
class dog 
{
//private
private:
int age, weight;
string color;

public:
  void bark(){
    cout << "WOOF!" << endl;}
    
    //setter methods
void setvalues(int age, int weight, string color){

//this is used when a class method has an argument of the same name as a class member.

this-> age = age;
this-> weight = weight;
this-> color = color;}
     //getter
     int getAge() {return age;}
     int getWeight() {return weight;}
     string getColor() {return color;}

};

int main()
{
  dog fido;
  
 fido.setvalues(3,15,"brown");
 
 dog pooch;
 
 pooch.setvalues(4,18,"gray");
  
  cout << "fido is a " << fido.getColor() << " dog " << endl;
  cout << " he is " << fido.getAge() << " years old" << endl;
  cout << "Fido weights " << fido.getWeight() << endl;
  fido.bark();
   cout << "Pooch is a " << pooch.getColor() << " dog " << endl;
  cout << " he is " << pooch.getAge() << " years old" << endl;
  cout << "Fido weights " << pooch.getWeight() << endl;
  pooch.bark();
}
No, this is used whenever you need a pointer to the instance, be it to store it somewhere or to pass it to another function.
Topic archived. No new replies allowed.