Hello everyone, I just cans find the pros and cons of explicitly using the this pointer to access members.
Its an exercise from my book:
It is legal but redundant to refer to members trough the this pointer. Discuss the pros and cons of explicitly using the this pointer to access members.
Well I have one pro: So we make sure that we are working on the current object, that it was called on.
Imagine if your class had two variables int a and int b, and you had a function member whose parameters were int a and int b, by default the function would use its own parameters before the class variables.
Sometimes you may need to instruct the function to not use the function parameters and use the class ones of the same name, thats where this comes in.
#include <iostream>
usingnamespace std;
class Calc
{
private:
int a, b;
public:
Calc() { a = 20; b = 30; }
int Add(int a, int b) { return a + b; }
int AddThis(int a, int b) { returnthis->a + this->b; }
};
int main()
{
Calc Test;
int num1 = 5, num2 = 11;
// i would expect the result from the following call
// to be 16 because function parameters take priority
// over class members.
cout << Test.Add(num1, num2) << endl;
// this should be 50, we have used the this-> to tell
// our function to use the class variables and not the
// function variables
cout << Test.AddThis(num1, num2);
}