the question is simple... is there any difference in using this->yourvariable or yourvariable directly for some reason?
I am not finding any problem with that, but I am using this-> a lot and would like to know if there is any difference before going further.
I saw a comment on a post here and I don't remember which thread, but the person said something about using the keyword "this".
Personally, I find it nice to use than the variable directly. It makes the code more easier and pretty.
Joe
In most cases there is no difference. But there are situations where it makes a difference:
class foo
{
int i;
void bar() {
int i = 3;
i; // refers to local i
this->i; // refers to the member i
}
};
Also, with templates you may need to qualify a member with this->
so that name lookup is delayed:
template<typename T>
struct A
{
int i;
T* p;
};
template<typename T>
struct B : A<T>
{
void foo() {
int k = this->i; // here this-> is required
}
};
A compiler that properly does the "two phase lookup" will complain in case you remove "this->" that it doesn't know what i is supposed to be. "this->" tells it that it's a member from a base class. Since the base class depends on a template parameter, lookup is delayed until the class template is instantiated.
No, there is no real difference, it is simply a scope qualifier. However, suppose a method
void SetFoo( Foo foo )
{
this->foo = foo;
}
where this->foo is a private member. Here it allows you to take a parameter with the same name as a class/instance variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With