What doees "this" keyword refer in this code block in c++?

Viewed 68
const newString& newString::operator=(const newString& rightStr)
{
    if(this!=&rightStr)
    {
        delete[] strPtr;
        strLength=rightStr.strLength;
        strPtr = newChar[strLength+1];
        strcpy(strPtr,rightStr.strPtr);
    }
    return* this;
}

I know it avoids self copy, but what does "this" keyword refer to? I mean I thought it was rightStr but then why would it chechk if its equal to itself?

2 Answers

In a non-static class method, the this keyword is defined by the C++ language as a pointer to the object that the current class method was invoked on.

In your case, this refers to the newString object on the left side of the assignment statement that invoked newString::operator=. For example, in the below code:

newString strSrc, strDest;
strDest = strSrc;

Inside of newString::operator=, this is a pointer to the strDest object, and rightStr is a reference to the strSrc object.

"This" keyword can be used to pass current object as a parameter to another method or it can be used to refer current class instance variable.

Related