1Every object in C++ has access to its own address through an important pointer called this pointer.
2The this pointer is an implicit parameter to all member functions.
3Therefore, inside a member function, this may be used to refer to the invoking object.
4
5Example:
6#include <iostream>
7using namespace std;
8class Demo {
9private:
10 int num;
11 char ch;
12public:
13 void setMyValues(int num, char ch){
14 this->num =num;
15 this->ch=ch;
16 }
17 void displayMyValues(){
18 cout<<num<<endl;
19 cout<<ch;
20 }
21};
22int main(){
23 Demo obj;
24 obj.setMyValues(100, 'A');
25 obj.displayMyValues();
26 return 0;
27}
28
1#include <iostream>
2class Entity
3{
4public:
5 int x, y;
6 Entity(int x, int y)
7 {
8 Entity*const e = this;// is a ptr to the the new instance of class
9 //inside non const method this == Entity*const
10 //e->x = 5;
11 //e->y =6;
12 this->x = x;
13 this->y = x;
14 }
15 int GetX()const
16 {
17 const Entity* e = this;//inside const function this is = const Entity*
18 }
19};
20
21int main()
22
23{
24 Entity e1(1,2);
25}