Here I am taking an example of overloading the increment operator:
class Digit
{
int m_digit;
public:
Digit (int value) //constructor
{
m_digit = value;
}
Digit& operator++();
int ret_dig (){return m_digit;}
};
Digit& Digit::operator++()
{
if (m_digit == 9)
m_digit = 0;
else ++m_digit;
return *this;
}
int main ()
{
Digit my_dig (5);
++my_dig;
return 0;
}
I have been told that local variables can't be returned. Isn't "this" a local variable? Here is what I think:
A pointer of type Digit is attached to the member function (overloaded operator function). When compiler sees the line ++my_dig, that is an instance of Digit class, it calls the member function. The address of the instance my_dig is passed as argument to the function and there is a hidden "const Digit*" named "this" to catch the argument. "this" is dereferenced(implicitly) to access m_digit, that is a member variable of class Digit. All the increment or wrapping is done inside the function and a reference to dereferenced "this" is then returned to the caller. Yes, this is the point to my confusion. If "this" is a local variable of type const Digit*, shouldn't it contain garbage when returned because "this" is going out of scope where the block ends haaa?