The This Pointer*
1 // the this pointer
2 #include <iostream.h>
3
4 class where
5 {
6 private:
7 char charray[10]; // occupies 10 bytes
8 public:
9 void reveal()
10 { cout << "My object's address is " << this << endl; }
11 };
12
13 void main()
14 {
15 where w1, w2, w3; // make three objects
16 w1.reveal(); // see where they are
17 w2.reveal();
18 w3.reveal();
19 }
Output from above:
My object's address is 0x0064FDEC My object's address is 0x0064FDE0 My object's address is 0x0064FDD4
Accessing This
1 // the this pointer referring to data
2 #include <iostream.h>
3
4 class what {
5 private:
6 int alpha;
7 public:
8 void tester() {
9 this->alpha = 11; // same as alpha = 11;
10 cout << this->alpha; // same as cout << alpha;
11 (*this).alpha = 12; // same as alpha = 12;
12 cout << (*this).alpha; // same as cout << alpha;
13 }
14 };
15
16 void main() {
17 what w;
18 w.tester();
19 }
Using This for Returning Values
1 // returns contents of the this pointer
2 #include <iostream.h>
3
4 class alpha {
5 private:
6 int data;
7 public:
8 alpha() { // no-arg constructor
9 }
10 alpha(int d) { // one-arg constructor
11 data = d;
12 }
13 void display() { // display data
14 cout << data;
15 }
16 alpha& operator = (alpha& a) { // overloaded = operator
17 data = a.data; // not done automatically
18 cout << "\nAssignment operator invoked";
19 return *this; // return copy of this alpha
20 }
21 };
22
23 void main() {
24
25 alpha a1(37);
26 alpha a2, a3;
27
28 a3 = a2 = a1; // invoke overloaded =
29 cout << "\na2="; a2.display(); // display a2
30 cout << "\na3="; a3.display(); // display a3
31 }
Output from above:
Assignment operator invoked Assignment operator invoked a2=37 a3=37