What is purpose of this
keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this
to call peer methods inside a class?

- 43,139
- 57
- 169
- 274

- 377
- 1
- 3
- 7
17 Answers
Two main uses:
To pass
*this
orthis
as a parameter to other, non-class methods.void do_something_to_a_foo(Foo *foo_instance); void Foo::DoSomething() { do_something_to_a_foo(this); }
- To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
(Although an initialization list is usually preferable to assignment in this particular example.)MessageBox::MessageBox(const string& message) { this->message = message; }

- 56,064
- 19
- 146
- 246
-
13+1. There's a third case: If you have a class template with a base class that depends on the template parameters, accessing members of the base class requires `this->` or `baseclass::` to delay name lookup. – sellibitze May 13 '10 at 18:04
-
Or to check for weird errors with this != NULL – josefx May 14 '10 at 10:57
-
4@josefx: That's one of those comments which make me regret that we cannot down-vote comments. – sbi May 14 '10 at 17:52
-
@sbi true, I should have added that 1) this != NULL only helps to understand that a member function may get called on an invalid object as foo->bar() is almost the same as bar(foo) 2) it should only be used for debugging and only if anything else already failed, which means almost never. – josefx May 15 '10 at 10:57
-
2@josefx: To me it seems that, besides some corner cases, a `this` pointer would usually be `NULL` in code that uses the classic `delete p; p=NULL;` anti pattern. In other words: in code that _manually fiddles with dynamic memory_ (and gets it wrong, of course). The way to solve such problems is not to put assertions in to catch its classic errors (note: _if at all,_ it should certainly be `assert(this);`). __The solution is to never write such code.__ – sbi May 15 '10 at 17:51
-
@sbi, if we could all write perfect code the world would be a much better place. I use the anti-pattern as you call it for two reasons - first to enhance the likelyhood that bad code will crash spectacularly without hiding, and second to make the core problem more obvious in debugging. I wouldn't litter my code with `assert`s just to catch this problem though. – Mark Ransom Aug 18 '11 at 21:50
-
1@Mark: IME `ptr = NULL` often actually ___hides___ the problem, because `if(ptr)` will then filter out that pointer before it is used at so many places in the code. As I said, the real solution to the problem is to 1) not to have pointers in scope that aren't attached to any objects, or 2) use smart pointers which can deal with this. – sbi Aug 22 '11 at 12:44
- Helps in disambiguating variables.
- Pass yourself as a parameter or return yourself as a result
Example:
struct A
{
void test(int x)
{
this->x = x; // Disambiguate. Show shadowed variable.
}
A& operator=(A const& copy)
{
x = copy.x;
return *this; // return a reference to self
}
bool operator==(A const& rhs) const
{
return isEqual(*this, rhs); // Pass yourself as parameter.
// Bad example but you can see what I mean.
}
private:
int x;
};

- 257,169
- 86
- 333
- 562
Consider the case when a parameter has the same name as a class member:
void setData(int data){
this->data = data;
}

- 131,333
- 52
- 229
- 284
The expression *this
is commonly used to return the current object from a member function:
return *this;
The this
pointer is also used to guard against self-reference:
if (&Object != this) {
// do not execute in cases of self-reference
-
(see also http://msdn.microsoft.com/en-us/library/y0dddwwd%28VS.80%29.aspx ) – sth May 13 '10 at 18:03
- Resolve ambgiguity between member variables/functions and those defined at other scopes
- Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
- Trigger IntelliSense in the IDE (though that may just be me).

- 8,709
- 6
- 42
- 49
-
2#3 -- I know some people who do that. I can always tell when I'm looking at code they wrote because it is uuuugly (well, for more reasons than just the extraneous `this->` all over the place). – Dan May 13 '10 at 17:48
It lets you pass the current object to another function:
class Foo;
void FooHandler(Foo *foo);
class Foo
{
HandleThis()
{
FooHandler(this);
}
};

- 44,851
- 20
- 112
- 171
Some points to be kept in mind
This pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
This pointer is not counted for calculating the size of the object.
This pointers are not accessible for static member functions.
This pointers are not modifiable
Look at the following example to understand how to use the 'this' pointer explained in this C++ Tutorial.
class this_pointer_example // class for explaining C++ tutorial
{
int data1;
public:
//Function using this pointer for C++ Tutorial
int getdata()
{
return this->data1;
}
//Function without using this pointer
void setdata(int newval)
{
data1 = newval;
}
};
Thus, a member function can gain the access of data member by either using this pointer or not. Also read this to understand some other basic things about this pointer

- 43,139
- 57
- 169
- 274
It allows you to get around members being shadowed by method arguments or local variables.

- 776,304
- 153
- 1,341
- 1,358
-
It can also help to improve readability if it is unclear what the member variables are i.e. `this->m_var = var`. – Chris May 13 '10 at 17:24
The this
pointer inside a class is a reference to itself. It's needed for example in this case:
class YourClass
{
private:
int number;
public:
YourClass(int number)
{
this->number = number;
}
}
(while this would have been better done with an initialization list, this serves for demonstration)
In this case you have 2 variables with the same name
- The class private "number"
- And constructor parameter "number"
Using this->number
, you let the compiler know you're assigning to the class-private variable.

- 5,590
- 1
- 25
- 33
For example if you write an operator=()
you must check for self assignment.
class C {
public:
const C& operator=(const C& rhs)
{
if(this==&rhs) // <-- check for self assignment before anything
return *this;
// algorithm of assignment here
return *this; // <- return a reference to yourself
}
};

- 16,144
- 10
- 57
- 99
The this
pointer is a way to access the current instance of particular object. It can be used for several purposes:
- as instance identity representation (for example in comparison to other instances)
- for data members vs. local variables disambiguation
- to pass the current instance to external objects
- to cast the current instance to different type

- 74,861
- 18
- 132
- 169
One more purpose is to chaining object: Consider the following class:
class Calc{
private:
int m_value;
public:
Calc() { m_value = 0; }
void add(int value) { m_value += value; }
void sub(int value) { m_value -= value; }
void mult(int value) { m_value *= value; }
int getValue() { return m_value; }
};
If you wanted to add 5, subtract 3, and multiply by 4, you’d have to do this: #include int main() { Calc calc; calc.add(5); // returns void calc.sub(3); // returns void calc.mult(4); // returns void
std::cout << calc.getValue() << '\n';
return 0;
}
However, if we make each function return *this, we can chain the calls together. Here is the new version of Calc with “chainable” functions:
class Calc
{
private:
int m_value;
public:
Calc() { m_value = 0; }
Calc& add(int value) { m_value += value; return *this; }
Calc& sub(int value) { m_value -= value; return *this; }
Calc& mult(int value) { m_value *= value; return *this; }
int getValue() { return m_value; }
};
Note that add(), sub() and mult() are now returning *this. Consequently, this allows us to do the following:
#include <iostream>
int main()
{
Calc calc;
calc.add(5).sub(3).mult(4);
std::cout << calc.getValue() << '\n';
return 0;
}
We have effectively condensed three lines into one expression.
Copied from :http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/

- 131
- 2
- 3
The double colon in c++ is technically known as "Unary Scope resolution operator". Basically it is used when we have the same variable repeated for example inside our "main" function (where our variable will be called local variable) and outside main (where the variable is called a global variable). C++ will alwaysexecute the inner variable ( that is the local one). So imagine you want to use the global variable "Conundrum" instead the local one just because the global one is expressed as a float instead of as an integer:
#include <iostream>
using namespace std;
float Conundrum=.75;
int main()
{
int Conundrum =75;
cout<<::Conundrum;
}
So in this case the program will use our float Conundrum instead of the int Conundrum.
Sometimes you want to directly have a reference to the current object, in order to pass it along to other methods or to store it for later use.
In addition, method calls always take place against an object. When you call a method within another method in the current object, is is equivalent to writing this->methodName()
You can also use this to access a member rather than a variable or argument name that "hides" it, but it is (IMHO) bad practice to hide a name. For instance:
void C::setX(int x) { this->x = x; }

- 88,451
- 51
- 221
- 321
For clarity, or to resolve ambiguity when a local variable or parameter has the same name as a member variable.

- 10,721
- 3
- 25
- 25
It also allows you to test for self assignment in assignment operator overloads:
Object & operator=(const Object & rhs) {
if (&rhs != this) {
// do assignment
}
return *this;
}

- 9,994
- 31
- 47
It also allows objects to delete themselves. This is used in smart pointers implementation, COM programming and (I think) XPCOM.
The code looks like this (excerpt from some larger code):
class counted_ptr
{
private:
counted_ptr(const counted_ptr&);
void operator =(const counted_ptr&);
raw_ptr_type _ptr;
volatile unsigned int _refcount;
delete_function _deleter;
public:
counted_ptr(raw_ptr_type const ptr, delete_function deleter)
: _ptr(ptr), _refcount(1), _deleter(deleter) {}
~counted_ptr() { (*_deleter)(_ptr); }
unsigned int addref() { return ++_refcount; }
unsigned int release()
{
unsigned int retval = --_refcount;
if(0 == retval)
>>>>>>>> delete this;
return retval;
}
raw_ptr_type get() { return _ptr; }
};

- 26,809
- 3
- 46
- 82