Tuesday, November 18, 2003

this

Yeah I know you don't HAVE to use it. It's not a universal convention. I just adopted it so that it's explicit. This way there are NO possible conflicts with local variables having the same name as member variables - you know exactly which one you're talking about. I also recently started adding "m_" before member variables. I guess either one will work.

There are generally conventions used with various frameworks. The STL has a few. MFC/.NET/Java all follow conventions. This makes it easier to read the code and follow what's going on.

Anyway, there is another use for the "this" variable. You could have two functions with the same name in your class, one constant and one NON-constant. For example...

class Person
{
private:
int m_age;

public:
int& age()
{
return this->m_age;
}

const int& age() const
{
return this->m_age;
}
};

Both those mehtods do exactly the same thing, except the first one returns it by reference (you can change it), and the second returns by const reference (you CAN'T change it).

Now, this is just a simple returning of a member data value. What if it was a more complicated method? You'd have to write that algorithm twice. You can use "this" to simplify and resuse...

int& age()
{
return this->m_age;
}

const int& age() const
{
return ( *this ).age();
}

You can't just call age() from the second method because it will be an infinite recursive call. Using "this"... it will call the first age(), which will return a reference. It will then change it to a const reference and return that. In c++ going from non-const to const is implicit.

No comments: