forked from SalikAli1234/Zero-to-Advance-OOP-Concepts-CPP
-
Notifications
You must be signed in to change notification settings - Fork 2
/
9_thisPointer.cpp
77 lines (64 loc) · 1.63 KB
/
9_thisPointer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*What is a this key Word in C++? Write a C++ program in which the setter function parameter name is same as the class data member name.What is the *this Pointer* in the C++?*/
/*The this keyword can be used for the two purposes firtsly to use the local variable names as same as the class data memebers name.Secondly it can be used for the function calls chaining in which the local object returns the refernce of the single object and in function chaining it updates the every previous function value also.*/
#include<iostream>
using namespace std;
class algebra
{
private:
int x;
int y;
public:
//setters
void setX(int x)
{
this->x=x;
}
void setY(int y)
{
this->y=y;
}
void setData(int x,int y)
{
this->x=x;
this->y=y;
}
//getters
int getX()
{
return x;
}
int getY()
{
return y;
}
void getData()
{
cout<<"The value of x = "<<x<<endl;
cout<<"The value of y = "<<y<<endl;
}
//member functions
algebra &value(int x)
{
this->x=x;
return *this;
}
algebra &incrementValue(int y)
{
this->x++;
this->y=y;
return *this;
}
};
int main()
{
algebra obj1;
algebra *obj2=new algebra;
obj1.setData(1,2);
obj2->setData(3,4);
obj1.getData();
obj2->getData();
obj1.value(100).incrementValue(200);
obj1.getData();//101,200--->chaining is sequential and the changes made to the object’s data members retains for further chaining calls.
// obj1.setX(90).setY(900);// error: invalid use of 'void'
return 0;
}