this in cpp code example

Example 1: What is This pointer? Explain with an Example.

Every object in C++ has access to its own address through an important pointer called this pointer.
The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.

Example:
#include <iostream>
using namespace std;
class Demo {
private:
  int num;
  char ch;
public:
  void setMyValues(int num, char ch){
    this->num =num;
    this->ch=ch;
  }
  void displayMyValues(){
    cout<<num<<endl;
    cout<<ch;
  }
};
int main(){
  Demo obj;
  obj.setMyValues(100, 'A');
  obj.displayMyValues();
  return 0;
}

Example 2: this keyword in cpp

this is a keyword that refers to the current instance of the class. 
 There can be 3 main usage of this keyword in C++. It can be used to 
 pass current object as a parameter to another method. 
 It can be used to refer current class instance variable.
   
#include <iostream>
using namespace std;
class Demo {
private:
  int num;
  char ch;
public:
  void setMyValues(int num, char ch){
    this->num =num;
    this->ch=ch;
  }
  void displayMyValues(){
    cout<<num<<endl;
    cout<<ch;
  }
};
int main(){
  Demo obj;
  obj.setMyValues(100, 'A');
  obj.displayMyValues();
  return 0;
}

Output:- 
  	100
	A

Example 3: this in c++

#include <iostream>
class Entity
{
public:
	int x, y;
	Entity(int x, int y)
	{
		Entity*const e = this;// is a ptr to the the new instance of class 
		//inside non const method this == Entity*const
		//e->x = 5;
		//e->y =6;
		this->x = x;
		this->y = x;
	}
	int GetX()const
	{
		const Entity* e = this;//inside const function this is = const Entity*
	}
};

int main()

{
	Entity e1(1,2);
}

Tags:

Cpp Example