The this keyword is used to represent an object that invokes the member function. It points to the object for which this function was called. It is automatically passed to a member function when it is called.
e.g. when you call A.func(), this will be set to the address of A.
e.g. when you call A.func(), this will be set to the address of A.
C++ - Explain the use of this pointer -
When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (ie the object on which the function is invoked). This pointer is known as this pointer. It is internally created at the time of function call.
The this pointer is very important when operators are overloaded.
Example: Consider a class with int and float data members and overloaded Pre-increment operator ++:
class MyClass
{
int i;
float f;
public:
MyClass ()
{
i = 0;
f = 0.0;
}
MyClass (int x, float y)
{
i = x; f = y;
}
MyClass operator ++()
{
i = i + 1;
f = f + 1.0;
return *this; //this pointer which points to the caller object
}
MyClass show()
{
cout<<”The elements are:\n” cout<<”\n
data members using this
}
};
{
int i;
float f;
public:
MyClass ()
{
i = 0;
f = 0.0;
}
MyClass (int x, float y)
{
i = x; f = y;
}
MyClass operator ++()
{
i = i + 1;
f = f + 1.0;
return *this; //this pointer which points to the caller object
}
MyClass show()
{
cout<<”The elements are:\n” cout<<”\n
data members using this
}
};
int main()
{
MyClass a;
++a; //The overloaded operator function ++()will return a’s this
pointer
a.show();
retun 0;
}
The o/p would be:
The elements are:
1
1.0
{
MyClass a;
++a; //The overloaded operator function ++()will return a’s this
pointer
a.show();
retun 0;
}
The o/p would be:
The elements are:
1
1.0

0 Comments:
Post a Comment