2

in the code below, it does not matter whether i put "this->" or remove it. it gives same output and result in both cases. So, what is the point of having the "this" pointer in C++? Are there other usages where it is essential? Thanks.

#include<iostream> using namespace std; class square{ int l; int w; public: square(int x, int y){ w = x; l = y; } int getArea(){ return w * l; }; bool AreaSmallerThan(square c){ if(this->getArea() < c.getArea()) return true; else return false; } }; int main(){ square A(2,3); square B(1,3); if(A.AreaSmallerThan(B)) cout<<"A is smaller than B."<<endl; else cout<<"A is NOT smaller than B."<<endl; return 0; } 
1
  • Well, the if -else statement is even more useless than the this-> in that function. It should be bool AreaSmallerThan(square c) { return getArea() < c.getArea(); } You may also want to change that parameter to square const& c to avoid an unnecessary copy. Commented Jan 28, 2014 at 4:38

4 Answers 4

7

TL;DR: It has it's uses. If you choose good naming practices, you generally won't need to use it often.

There are a number of cases where you would want a "pointer to the current object", for example:

struct Foo { void MakeCallback(eventid_t eventId) { scheduleCallback(eventId, callbackProxyFn, this); } static void callbackProxyFn(eventid_t eventId, Foo* foo) { // call 'callback' on the relevant object instance. foo->callback(eventId); } void callback(eventid_t eventId); }; 

It can also be used to resolve conflicts between names in the current object and other scopes, if you choose to use terrible naming conventions.

void Foo::bar(int n) { this->n = n; } 

You could avoid this (pun intended) scenario, as is common practice, by prefixing statics, globals and members:

class Player { int m_score; public: Player(int score) : m_score(score) {} }; Player g_player1; static Player s_login; // yeah, I know, terrible, just an example tho. 

A common use is in eliminating self in copy/comparison operators:

bool Foo::operator==(const Foo& rhs) const { if (this == &rhs) return true; ... } 

You can also use it to produce a reference to the current object:

foo(const Foo&); void foo(*this); 
Sign up to request clarification or add additional context in comments.

Comments

7

Yes there are times it is essential. A classic case is in operator=, to avoid destroying resources during self-assignment.

for example https://stackoverflow.com/a/3975092/103167

Set& Set::operator=(const Set& setEqual) { //first check for self assignment if (&setEqual == this) cout << "this is self assignment"; return *this; } 

(Note that this isn't needed when using the copy-and-swap idiom)

Accessing members via this is also frequently seen in template code which inherits from a template parameter. Those inherited names can only be found during second phase lookup, which means they need to be qualified with this->

2 Comments

"...which means they need to be qualified with this->" I encountered this one once, and I thought it was a bug in the compiler. Does this rule has a name I can look up?
@C.R.: Dependent names in two-phase lookup. See 14.6.2.1p5 in n3936
6

Random example...what if you had passed an int w, int l into your getArea() function...then you need to use the this keyword to differentiate between the local parameter

int getArea(int w, int l){ return this->w * this->l; }; 

Another common example might be move assignment. I have pasted an example from a Tree datastructure project I coded.

 /* move assignment */ TreeSet& operator= (TreeSet&& rhs) { clearAll(rootPtr); this->rootPtr = rhs.rootPtr; rhs.rootPtr = nullptr; return *this; } 

And finally another example for an iterator I wrote...when overloading the ++ operator on an iterator, you want to return the resulting iterator..

 /* Update the current pointer to advance to the node * with the next larger value */ const_iterator& operator++ () { //I have deleted all the logic for the sake of not taking up a ton of space.. return *this; } 

7 Comments

That's hardly essential. Most of us consider it terrible style to intentionally create name conflicts.
perhaps, as I said, "Random example" ..first thing that jumped into my head... it is however a legitimate use for the keyword...
It's also not needed. ClassName::w and ClassName::l also work.
return *this is a great example though. +1
I have included another example outside of my first example
|
0

Generally speaking, the 'this' pointer can be useful when an instance of a class is invoking some method and the instance itself needs to be passed from within the method to some function outside of the class.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.