There are several cases of using this , and there are others where using the this pointer is one way to solve the problem.
1) Alternatives are available . To eliminate the ambiguity between local variables and class members, as @ASk shows .
2) There is no alternative: To return a pointer or a link to this from a member function. This is often done (and should be done) by overloading operator+ , operator- , operator= , etc.:
class Foo { Foo& operator=(const Foo& rhs) { return * this; } };
Doing this resolves the idiom known as the " chain of methods ", where you perform several operations on an object in a single line of code. For example:
Student st; st.SetAge (21).SetGender (male).SetClass ("C++ 101");
Some consider this consise, others consider it an abomination. Count me in the last group.
3) There is no alternative:. To resolve names in dependent types. This happens when using templates, as in this example:
#include <iostream> template <typename Val> class ValHolder { private: Val mVal; public: ValHolder (const Val& val) : mVal (val) { } Val& GetVal() { return mVal; } }; template <typename Val> class ValProcessor : public ValHolder <Val> { public: ValProcessor (const Val& val) : ValHolder <Val> (val) { } Val ComputeValue() { // int ret = 2 * GetVal(); // ERROR: No member 'GetVal' int ret = 4 * this->GetVal(); // OK -- this tells compiler to examine dependant type (ValHolder) return ret; } }; int main() { ValProcessor <int> proc (42); const int val = proc.ComputeValue(); std::cout << val << "\n"; }
4) Available alternatives . As part of the coding style, member variables are used to document variables, not local variables. I prefer a different naming scheme in which varibales members can never have the same name as local ones. I am currently using mName for members and name for local users.
John Dibling Jun 15 '09 at 4:32 2009-06-15 04:32
source share