I have read the tutorials, heard explanations, etc; yet I cannot grasp the understanding of the "this" keyword.
Any help would be greatly appreciated.
I have read the tutorials, heard explanations, etc; yet I cannot grasp the understanding of the "this" keyword.
Any help would be greatly appreciated.
Have you had any experience with class usage before? if not, please consult the FAQ section. Otherwise, just read on...
the 'this' pointer is pre-defined, and it points to the CURRENT CLASS INSTANCE, or object. For example, with a class CBox, if you call a member function within this class (i.e. CBox::CBox(); ), the 'this' pointer will be set to the address of the CBox object which you created (i.e. CBox myBox; ).
Here it is in code:
//---------------------------------------------------------------------------------
class CBox
{
public:
CBox()
{
cout << " 'this' pointer in CBox::CBox(): " << this << endl;
}
};
int main()
{
cout << " 'this' pointer in main(): " << this << endl;
CBox myBox;
return 0;
}
//---------------------------------------------------------------------------------
as you can see, the 'this' pointer is different when referenced within the CBox class constructor compared to in main(). 'this' is useful in many ways, such as in overloaded assignment operator functions, where you MUST check first to see whether or not the class object to be copied occupies the same address in memory. if so, it sets 'this' to the parameter, then returns. an example of this follows:
//---------------------------------------------------------------------------------
CBox CBox:perator =(const CBox& rBox)
{
if(this == &rBox) // Is address of arg. the same?
return *this; // Return contents of this ptr.
tLength = rBox.tLength; // Initialize data members
tWidth = rBox.tWidth; //
tHeight = rBox.tHeight; //
return *this; // Return de-referenced ptr.
}
//---------------------------------------------------------------------------------
other uses include just finding the address of the current class object, and using it with the MS compiler at design-time to query ths current members of the class without using the project window (that's fairly subtle, but useful, nonetheless).
i hope you now have a better understanding of how to use the 'this' pointer!
Regards,
Peter Kimberley
[email protected]
Ahhh, I understand it now Thanks kindly for your time!