Using the this-> pointer or directly calling the method/accessing the variable

Just a quick question with this code:

1
2
3
4
5
6
7
8
9
10
11
class Foo
{
    Foo();
    void Bar();
    int a;
};

Foo::Foo()
{
    a = 10;
}


To access the 'a' variable within the class, should I do this:

1
2
3
4
void Foo::Bar()
{
    int b = this->a;
}


or this:

1
2
3
4
void Foo::Bar()
{
    int b = a;
}


Is one more preferable than the other, or is it a matter of opinion?
Last edited on
By default, those guys are private consequently other objects cannot access them.

But if you make them public, then you can access them.
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
#include <iostream>
class Foo
{
public:
	Foo();
	void Bar();
	void Bag();
//private:
	int a;
};

Foo::Foo()
{
	a = 10;
}
void Foo::Bar()
{
	int b = this->a;
	std::cout << b << std::endl;
}
void Foo::Bag()
{
	int b = a;
	std::cout << b << std::endl;
}
int main()
{
	Foo f;
	f.Bar();
	f.Bag();
        
   return 0;
}


Hope that helps.
Last edited on
I meant within the object, like I am accessing the class variable in one of the class's member functions. I have tried both versions, and they both work, but I am curious which is more preferable. Thanks in advance.
Is one more preferable than the other, or is it a matter of opinion?

In most cases it is just a matter of opinion (preference). My preference is to only use the this-> syntax when absolutely necessary such as when you have a parameter with the same name.

By default, those guys are private consequently other objects cannot access them.

Yes classes have default private access, however in the snippets shown the only access being attempted is from within the class so the access specifier is not relevant to the question asked.


@jlb
Yes classes have default private access, however in the snippets shown the only access being attempted is from within the class so the access specifier is not relevant to the question asked.

Thanks for the correction.
Topic archived. No new replies allowed.