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}
1 this is a keyword that refers to the current instance of the class.
2 There can be 3 main usage of this keyword in C++. It can be used to
3 pass current object as a parameter to another method.
4 It can be used to refer current class instance variable.
5
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
29Output:-
30 100
31 A