When should I explicitly write this->member
in a method of
a class?

- 98,632
- 24
- 142
- 234
-
21I'm sure this is a dupe, but it is of course unsearchable. Not for the first time, I wish the this pointer was called self! – Jun 14 '09 at 18:11
-
6Not only that, I wish it were a reference. – rlbond Jun 14 '09 at 18:25
-
2Same. :| Here is why, by the way: http://www.research.att.com/~bs/bs_faq2.html#this – GManNickG Jun 14 '09 at 18:26
-
1Yup, duplicate. See questions 146989, 577243. SO Search tip: you can also search for strings you expect in the answer. In this case I used "template name lookup" – MSalters Jun 15 '09 at 07:54
-
11This method obviously doesn't work if the person doesn't know the answer. – ASk Jun 15 '09 at 16:10
-
1@GManNickG That link no longer works, is there another? – John H. Jul 15 '16 at 16:24
-
4@JohnH.: Hm, looks like `research.att.com/~bs/` is now `stroustrup.com`. New link: http://www.stroustrup.com/bs_faq2.html#this – GManNickG Jul 17 '16 at 19:29
12 Answers
Usually, you do not have to, this->
is implied.
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this->
is explicitly required.
Consider the following code:
template<class T>
struct A {
T i;
};
template<class T>
struct B : A<T> {
T foo() {
return this->i; //standard accepted by all compilers
//return i; //clang and gcc will fail
//clang 13.1.6: use of undeclared identifier 'i'
//gcc 11.3.0: 'i' was not declared in this scope
//Microsoft C++ Compiler 2019 will accept it
}
};
int main() {
B<int> b;
b.foo();
}
If you omit this->
, some compilers do not know how to treat i
. In order to tell it that i
is indeed a member of A<T>
, for any T
, the this->
prefix is required.
Note: it is possible to still omit this->
prefix by using:
template<class T>
struct B : A<T> {
int foo() {
return A<T>::i; // explicitly refer to a variable in the base class
//where 'i' is now known to exist
}
};
-
10This might be a silly question, but I don't understand why `i` might not exist in `A`. Could I get an example? – Cam Jackson Dec 19 '13 at 01:08
-
1@CamJackson I tried the code on visual studio. the results are the same no matter "this->" existed or not. Any idea? – Peng Zhang Jan 12 '14 at 10:57
-
14@CamJackson: One can specialize classes on type: `template<> struct A
{ float x; };` – Macke Dec 03 '14 at 07:33 -
"Note: it is possible to still omit `this->` prefix by using `using`" Then you need to be careful with virtual functions. – L. F. Apr 26 '19 at 13:20
-
5@PengZhang: The Visual Studio compiler used to ignore the need for "this" in these cases, which is not C++-Standard compliant, see [Microsoft Docs](https://learn.microsoft.com/de-de/cpp/build/reference/permissive-standards-conformance?view=vs-2019#look-up-members-in-dependent-base) for details. – Kyrion Dec 05 '19 at 15:27
If you declare a local variable in a method with the same name as an existing member, you will have to use this->var to access the class member instead of the local variable.
#include <iostream>
using namespace std;
class A
{
public:
int a;
void f() {
a = 4;
int a = 5;
cout << a << endl;
cout << this->a << endl;
}
};
int main()
{
A a;
a.f();
}
prints:
5
4

- 737
- 4
- 7
-
1I would better use cout << A::a << endl; instead. ``this" is unimportant in this case. – siddhant3s Jun 15 '09 at 00:15
-
5I would rather just avoid the name clash with conventions like "m_a" or "a_". – Tom Jun 15 '09 at 05:28
There are several reasons why you might need to use this
pointer explicitly.
- When you want to pass a reference to your object to some function.
- When there is a locally declared object with the same name as the member object.
- When you're trying to access members of dependent base classes.
- Some people prefer the notation to visually disambiguate member accesses in their code.

- 32,009
- 9
- 68
- 103
Although I usually don't particular like it, I've seen others use this-> simply to get help from intellisense!

- 44,114
- 19
- 59
- 88
-
Why don't you like it? I think it reduces cognitive burden thinking about is this local var or a data member. – User 10482 Jul 07 '23 at 17:10
There are few cases where using this
must be used, and there are others where using the this
pointer is one way to solve a problem.
1) Alternatives Available: To resolve ambiguity between local variables and class members, as illustrated by @ASk.
2) No Alternative: To return a pointer or reference to this
from a member function. This is frequently done (and should be done) when overloading operator+
, operator-
, operator=
, etc:
class Foo
{
Foo& operator=(const Foo& rhs)
{
return * this;
}
};
Doing this permits an idiom known as "method chaining", where you perform several operations on an object in one line of code. Such as:
Student st;
st.SetAge (21).SetGender (male).SetClass ("C++ 101");
Some consider this consise, others consider it an abomination. Count me in the latter group.
3) No Alternative: To resolve names in dependant types. This comes up when using templates, as in this example:
#include <iostream>
template <typename Val>
class ValHolder
{
private:
Val mVal;
public:
ValHolder (const Val& val)
:
mVal (val)
{
}
Val& GetVal() { return mVal; }
};
template <typename Val>
class ValProcessor
:
public ValHolder <Val>
{
public:
ValProcessor (const Val& val)
:
ValHolder <Val> (val)
{
}
Val ComputeValue()
{
// int ret = 2 * GetVal(); // ERROR: No member 'GetVal'
int ret = 4 * this->GetVal(); // OK -- this tells compiler to examine dependant type (ValHolder)
return ret;
}
};
int main()
{
ValProcessor <int> proc (42);
const int val = proc.ComputeValue();
std::cout << val << "\n";
}
4) Alternatives Available: As a part of coding style, to document which variables are member variables as opposed to local variables. I prefer a different naming scheme where member varibales can never have the same name as locals. Currently I'm using mName
for members and name
for locals.

- 1
- 1

- 99,718
- 31
- 186
- 324
-
For point 3, when you say "no alternate", there actually are a few other ways: 1) `int ret = 6 * VahHolder
::GetVal();` or 2) in the class (not function) `using ValHolder – Chris Uzdavinis Feb 25 '22 at 13:47::GetVal;` also makes unqualified lookup work for GetVal, even in a dependent context. https://godbolt.org/z/n5PY3j51c
- Where a member variable would be hidden by a local variable
- If you just want to make it explictly clear that you are calling an instance method/variable
Some coding standards use approach (2) as they claim it makes the code easier to read.
Example:
Assume MyClass has a member variable called 'count'
void MyClass::DoSomeStuff(void)
{
int count = 0;
.....
count++;
this->count = count;
}

- 5,694
- 1
- 28
- 32
The other uses for this (as I thought when I read the summary and half the question... .), disregarding (bad) naming disambiguation in other answers, are if you want to cast the current object, bind it in a function object or use it with a pointer-to-member.
Casts
void Foo::bar() {
misc_nonconst_stuff();
const Foo* const_this = this;
const_this->bar(); // calls const version
dynamic_cast<Bar*>(this)->bar(); // calls specific virtual function in case of multi-inheritance
}
void Foo::bar() const {}
Binding
void Foo::baz() {
for_each(m_stuff.begin(), m_stuff.end(), bind(&Foo:framboozle, this, _1));
for_each(m_stuff.begin(), m_stuff.end(), [this](StuffUnit& s) { framboozle(s); });
}
void Foo::framboozle(StuffUnit& su) {}
std::vector<StuffUnit> m_stuff;
ptr-to-member
void Foo::boz() {
bez(&Foo::bar);
bez(&Foo::baz);
}
void Foo::bez(void (Foo::*func_ptr)()) {
for (int i=0; i<3; ++i) {
(this->*func_ptr)();
}
}
Hope it helps to show other uses of this than just this->member.

- 24,812
- 7
- 82
- 118
One other case is when invoking operators. E.g. instead of
bool Type::operator!=(const Type& rhs)
{
return !operator==(rhs);
}
you can say
bool Type::operator!=(const Type& rhs)
{
return !(*this == rhs);
}
Which might be more readable. Another example is the copy-and-swap:
Type& Type::operator=(const Type& rhs)
{
Type temp(rhs);
temp.swap(*this);
}
I don't know why it's not written swap(temp)
but this seems to be common.

- 65,341
- 56
- 178
- 228
-
In your last case, note that you can call a non-`const` member function on a temporary (`Type(rhs).swap(*this);` is legal and correct) but a temporary cannot bind to a non-const reference parameter (compiler rejects `swap(Type(rhs));` as well as `this->swap(Type(rhs));`) – Ben Voigt Mar 18 '19 at 14:51
You only have to use this-> if you have a symbol with the same name in two potential namespaces. Take for example:
class A {
public:
void setMyVar(int);
void doStuff();
private:
int myVar;
}
void A::setMyVar(int myVar)
{
this->myVar = myVar; // <- Interesting point in the code
}
void A::doStuff()
{
int myVar = ::calculateSomething();
this->myVar = myVar; // <- Interesting point in the code
}
At the interesting points in the code, referring to myVar will refer to the local (parameter or variable) myVar. In order to access the class member also called myVar, you need to explicitly use "this->".

- 9,179
- 7
- 42
- 59
-
This is the one use of `this->` that's trivial to avoid (just give the local variable a different name). All the really interesting uses of `this` are not even mentioned by this answer. – cmaster - reinstate monica Dec 02 '14 at 21:17
The main (or I can say, the only) purpose of this
pointer is that it points to the object used to invoke a member function.
Base on this purpose, we can have some cases that only using this
pointer can solve the problem.
For example, we have to return the invoking object in a member function with argument is an same class object:
class human {
...
human & human::compare(human & h){
if (condition)
return h; // argument object
else
return *this; // invoking object
}
};

- 5,889
- 2
- 20
- 44
You need to use this
to disambiguate between a parameters/local variables and member variables.
class Foo
{
protected:
int myX;
public:
Foo(int myX)
{
this->myX = myX;
}
};

- 339,232
- 124
- 596
- 636
-
2No, you don't *need* it, you can *use* it. You can also use a different name for the function argument, which has the advantage of not having two entities with the same name. – cmaster - reinstate monica Dec 02 '14 at 21:14
I found another interesting case of explicit usage of the "this" pointer in the Effective C++ book.
For example, say you have a const function like
unsigned String::length() const
You don't want to calculate String's length for each call, hence you want to cache it doing something like
unsigned String::length() const
{
if(!lengthInitialized)
{
length = strlen(data);
lengthInitialized = 1;
}
}
But this won't compile - you are changing the object in a const function.
The trick to solve this requires casting this to a non-const this:
String* const nonConstThis = (String* const) this;
Then, you'll be able to do in above
nonConstThis->lengthInitialized = 1;

- 5,752
- 5
- 49
- 59
-
3Or you could make `length` mutable, or even put it in a nested struct. Casting away constness is almost never a good idea. – Richard J. Ross III Feb 04 '13 at 18:21
-
4Please don't. If the member is to be changed from `const` member functions, the it should be `mutable`. Otherwise you are making life more complicated for you an other maintainers. – David Rodríguez - dribeas Feb 04 '13 at 18:24