I'm working on some code and I see in many methods that call other
methods of the same class prefix a this-> to the method being called,
i.e.
class X::methodA()
{
this->methodB();
}
And they are not even static methods. Isn't the this-> redundant?
Please explain.
Thank you.
In the example code above I assume you meant to type "return_type"
instead of "class"?
You are correct in that the "this->" part of the invocation of
methodB() is not required (assuming methodB() belongs to the same
class as methodA(), or a base class of methodA() ). It does document
to anyone reading the code that methodB() is being invoked with the
same object that invoked methodA(). This is the same reason that some
C++ programmers will invoke a global function like this:
::global_func(): // The :: operator signals that global_func() is not
a method of a class.
You mention that they are not even static methods. An interesting
comment! In my C++ courses I teach that it is extremely bad
programming form to invoke a static member function in any of the
following ways:
object.static_method();
ptr->static_method();
this->static_method();
Why? Because all 3 invocations give the casual observer the
impression that static_method() is normal method rather than a static
method. Instead it should be invoked in this way:
class_name::static_method();
I hope that answers your question.
Cheers,
Bob