this Object-Classes

closed account (EwCjE3v7)
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.

Thank you in advance
to avoid semantic differences, since in the class template class member's name is considered a non-dependent name

example found on the internet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

int i = 1;

struct R
{
  int i;
  R(): i(2) { }
};

template<typename T>
struct S : T
{
  void f()
  {
    std::cout << i << ' '     // selects ::i
              << this->i      // selects R::i
              << std::endl;
  }
};

int main()
{
  S<R>().f();
}
Last edited on
closed account (EwCjE3v7)
Sorry, I do not understand the above. I havnt done templates. And I believe the question is to say what is good and bad about them

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.

Take the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#include <iostream>
using namespace 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) { return this->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);

}


Hope this helps answer your question.
Topic archived. No new replies allowed.