Lesson 9 | The this pointer in C++ |
Objective | Use this pointer to print out the location |
this pointer in C++
Use the C++ this
pointer to print out the location of all its variables. The keyword this
denotes an implicitly declared self-referential pointer.
A this
pointer can be used only in a nonstatic member function and cannot be modified. Here is an example of a simple illustration of its use:
#include <iostream.h>
//The this pointer
class c_pair {
public: void init(char b) {
c2 = 1 + (c1 = b);
}
c_pair increment() {
c1++;
c2++;
return (*this);
}
c_pair* where_am_I() {
return this;
}
void print() {
cout << c1 << c2 << '\t';
}
private: char c1, c2;
};
int main(){
c_pair a, b;
a.init('A');
a.print();
cout << " is at " << a.where_am_I() << endl;
b.init('B');
b.print();
cout << " is at " << b.where_am_I() << endl;
b.increment().print();
}
The member function increment
uses the implicitly provided pointer this
to return the newly incremented value of both c1
and c2
.
The member function where_am_I
returns the address of the given object.
The this
keyword provides for a built-in self-referential pointer. It is as if c_pair
implicitly declared the private member c_pair* const this
.
Variable Memory Allocation -Exercise