In C++, this is a keyword that refers to the current instance of a class and this pointer holds the address or points to the current object of the class. Also, only the member functions have this pointer.
Members like friend functions do not have this pointer as they are not members of the class.
Example of this pointer in C++
Let us see an example of C++ this pointer that refers to the fields of the current class.
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 | #include <iostream> using namespace std; class Student { public: int roll; //fields string name; float score; Student(int roll, string name, float score) { this->roll = roll; this->name = name; this->score = score; } void print() { cout << "Roll No: " << roll << endl; cout << "Name: " << name << endl; cout << "Score: " << score << endl << endl; } }; int main(void) { //creating Object Student s1 = Student(1101, "John", 80); Student s2 = Student(1102, "Emma", 95); s1.print(); s2.print(); return 0; } |
Output:
Roll No: 1101
Name: John
Score: 80
Roll No: 1102
Name: Emma
Score: 95