When should i use the "this" pointer?

Nov 15, 2014 at 4:57am
I know the pointer returns the instance of a class but.. the thing i don't understand is when i should use "this" pointer.

Should i only use the pointer when i have overloaded an operator in a class function that uses the class name as a return type?

Last edited on Nov 15, 2014 at 5:01am
Nov 15, 2014 at 7:56am
there is another application.
if parameter's name of class's member function is same as the class member variable.
for example:

1
2
3
4
5
6
7
8
class A{
 public:
     void setx(int x){
          this->x = x;
     }
 private:
      int x;
}


in above code, member functionsetx()'s parameter name is as same as its member field x. in this situation, you must use keywordthis


Nov 15, 2014 at 9:30am
The this keyword is also useful if you want to pass the object to a function.
1
2
3
4
5
6
7
8
void bar(A&);

class A{
 public:
     void foo(){
          bar(*this);
     }
};
Topic archived. No new replies allowed.