The this Pointer:
-C++
provides a special in-build pointer know as this
pointer.
-this pointer is a local pointer variable in every member function.
-this pointer needs no declaration
-Its scope is limited to the member function.
-Friend functions are not member functions thus they do not have this pointer.
-Static member functions do not have this pointer
-this pointer is of type of that class of which function is a member.
-this pointer is a local pointer variable in every member function.
-this pointer needs no declaration
-Its scope is limited to the member function.
-Friend functions are not member functions thus they do not have this pointer.
-Static member functions do not have this pointer
-this pointer is of type of that class of which function is a member.
Example:
#include<iostream.h>
#include<conio.h>
class
complex
{
private:
int a,b;
public:
void getdata()
{
cout<<"Enter real and img
part";
cin>>a>>b;
}
void show()
{
cout<<"\na="<<a<<" b="<<b;
}
complex sumgreater(complex c)
{
if((a+b) > (c.a+c.b))
return(*this);
else
return(c);
}
};
int
main()
{
complex c1,c2,c3;
c1.getdata();
c2.getdata();
c3=c1.sumgreater(c2);
c3.show();
getch();
}
In the above example:
1.Observe the member function
sumgreater(), its job to return an object whose sum of member variable is
greater among two objects.
2.In the line c3=c1.sumgreater(c2); sumgreater() function is called by object c1, thus the address of c1 is passed implicitly to the member function sumgreater(), which is then received by pointer this.
3.We also passes an object c2 to function sumgreater(), which is received in object c.
4.If the sum of data stored in a and b of c1 is greater than the sum of data stored in a and b of c2( represented by c in sumgreater()) then object c1 has to be returned. The problem is how to represent caller object c1 in function sumgreater().
5.The problem is solved by using this pointer, as this contains the address of c1, *this is used to represent caller object (that is c1 in our example).
No comments:
Post a Comment