About Lesson
The ‘this’ is a pointer that points to the object for which ‘this’ function was called.
//Example C++ program to show how this pointer can be used to inside its own class
#include<iostream>
using namespace std;
class sample
{
int a,b;
public:
void getdata()
{
a=10;
b=20;
}
void showMemData()
{
cout<<"Value of A displaying directly : "<<a<<endl;
cout<<"Value of B displaying directly : "<<b<<endl;
cout<<"Value of A through this pointer : "<<this->a<<endl;
cout<<"Value of B through this pointer : "<<this->b<<endl;
}
void showMemAddr()
{
cout<<endl;
cout<<"Address of Current Object is : "<<this<<endl;
cout<<"Address of A for Current Object is :"<<&a<<endl;
cout<<"Address of B for Current Object is :"<<&b<<endl;
}
};
main()
{
sample s1,s2;
s1.getdata();
cout<<endl<<"Details of S1 Object: "<<endl;
s1.showMemData();
s1.showMemAddr();
cout<<"\n"<<"Details of S2 Object: "<<endl;
s2.getdata();
s2.showMemData();
s2.showMemAddr();
}
//Example C++ program to show how this pointer can be used to solve ambiguity between local variables and data members
#include<iostream>
using namespace std;
class sample
{
int a,b;
public:
void getdata(int a,int b)
{
//this->a=a;
(*this).a=a;
//this->b=b;
(*this).b=b;
}
void showdata()
{
cout<<"Value of A is: "<<a<<endl;
cout<<"Value of B is: "<<b<<endl;
}
};
main()
{
sample s;
s.getdata(10,20);
s.showdata();
}