This Keyword In Cpp

The keyword this:

The keyword this represents a pointer to the object whose member function is being executed. It is a pointer to the object itself.

One of its uses can be to check if a parameter passed to a member function is the object itself. For example,

CODE/PROGRAM/EXAMPLE
//this keyword
#include <iostream>
using namespace std;
class CDummy {
public:
int isitme (CDummy& param);
};
int CDummy::isitme (CDummy& param)
{
if (&param == this) return true;
else return false;
}
int main () {
CDummy a;
CDummy* b = &a;
if ( b->isitme(a) )
cout << “yes, &a is b”;
return 0;
}

O/P: yes, &a is b

It is also frequently used in operator= member functions that return objects by reference (avoiding the use of temporary objects).

Following with the vector's examples seen before we could have written an operator= function similar to this one:

Syntax
CVector& CVector::operator= (const CVector& param)
	{
	  x=param.x;
	  y=param.y;
	  return *this;
	}

In fact this function is very similar to the code that the compiler generates implicitly for this class if we do not include an operator= member function to copy objects of this class.

#this_keyword_in_c++ #this_keyword_in_cpp #example_of_this_keyword_in_c++

(New page will open, for Comment)

Not yet commented...