C++ this pointer
'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to a member function when it is called. Consider the following simple example:
class Student{
int id;
.....
.....
};
id=10;
this->id=10;
return *this;
C++ 'this' Example 1
#include<iostream>
using namespace std;
class Student
{
private:
int id;
public:
void setId (int id)
{
this->id = id; //retrieve the object's 'id' hidden by the private
variable 'id'
}
void printId() { cout << "id = " << id << endl; }
};
int main()
{
Student obj;
int id = 10;
obj.setId(id);
obj.printId();
return 0;
}
id=10
C++ 'return *this' Example 2
#include<iostream>
#include<cstring>
using namespace std;
class student
{
private:
char name[20];
int mark;
public:
student(char *n, int m){
strcpy(name,n);
mark = m;
}
student greater(student & a){
if(a.mark>=mark){
return a; //return when s1.greater(s2); is call
}
else{
return *this; //return when s1.greater(s3); is call
}
}
void display(void){
cout<< "Name: "<<name<<endl<<"Mark: "<<mark<<endl;
}
};
int main()
{
student s1("Ajay",70);
student s2("Lucky",60);
student s3("Raj",80);
student s = s1.greater(s2);
cout<< "Greater mark: "<<endl;
s.display();
s = s1.greater(s3);
cout<< "Greater mark: "<<endl;
s.display();
return 0;
}
Greater mark: Name: Ajay Mark: 70 Greater mark: Name: Raj Mark: 80