Search code examples
c++templatesinheritancethisname-lookup

Using the this pointer in a dependent derived class template


In the example pointers/countingptr.hpp of the book C++ Templates - The Complete Guide members of the derived dependent class CountingPtr are referred to using the this pointer. Why is this necessary in this example?

I'm aware that the this pointer is required in order to name members of a dependent base class template. Surely the this pointer is not required in dependent derived class template also?


Solution

  • I believe it's just a style of the guy who was making this code. Some people prefer putting this-> in front of anything that is related to a class inside that class. That indeed may sometimes be useful if you are doing funny things like:

    void foo( int a )
    {
    this->a = a;
    }
    

    or if you just think this increases readability. However, if you use it too much, it will be a mess:

    this->a = this->b * this->c - this->foo( this->d, this->bar() );