When should I use “this” in a class?

The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors … Read more

Javascript “this” pointer within nested function

In JavaScript the this object is really based on how you make your function calls. In general there are three ways to setup the this object: someThing.someFunction(arg1, arg2, argN) someFunction.call(someThing, arg1, arg2, argN) someFunction.apply(someThing, [arg1, arg2, argN]) In all of the above examples the this object will be someThing. Calling a function without a leading … Read more

In a templated derived class, why do I need to qualify base class member names with “this->” inside a member function?

C++ answer (general answer) Consider a template class Derived with a template base class: template <typename T> class Base { public: int d; }; template <typename T> class Derived : public Base<T> { void f () { this->d = 0; } }; this has type Derived<T>, a type which depends on T. So this has … Read more

When should I make explicit use of the `this` pointer?

Usually, you do not have to, this-> is implied. Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this-> is explicitly required. Consider the following code: template<class T> struct A { int i; }; template<class T> struct B … Read more