Reputation: 409
I was wondering is there was an advantage of any kind by using 'this' to reference class members, rather than not using it, in c++?
for example...
class Test
{
public:
Test();
void print_test()
{
std::cout << this -> m_x // Using 'this'
<< endl;
std::cout << m_x // Rather than referencing 'm_x' this way
<< endl;
}
private:
int m_x;
int m_y;
};
Upvotes: 3
Views: 130
Reputation: 453
Sometimes it's just a convention.
The basic idea is that we usually needs to use this->
to avoid naming conflicts:
class Value
{
public:
Value(): value(0), valueSet(false) {}
void setValue(int value) {
//value = value; ( WRONG : Naming conflict )
this->value = value; // Use this-> to distinguish between them
valueSet = true;
}
private:
int value;
bool valueSet;
}
Now the statement valueSet = true;
without this->
looks ugly. So people prefer to prefix this->
to make all things look consistent:
void setValue(int value) {
this->value = value;
this->valueSet = true; // Isn't this consistent and beautiful?
}
But to my knowledge of C++, this pattern is not widely used. If you'd ever looked at some Java source code, prefixing this.
before member field accesses is very common.
PS: Another possible reason is maybe people just want to emphasize it is a member field, not something else. Since most simple editors are not capable of highlighting such fields, it can improve code readability.
Upvotes: 2
Reputation: 16824
No, there is no performance difference. To the compiler, the meanings are identical.
Well, almost... the only time you specifically need to say this
is if you have a variable of the same name in an inner scope that shadows the member variable (which is considered bad form anyway), or funny cases where you have a templated base class and you need to tell the compiler that a name refers to a base class member (this is pretty rare though).
Upvotes: 5
Reputation: 436
No.. Otherwise everyone would've written code like this. Maybe somebody thought it easy to read. Maybe he was a java developer.
Upvotes: 0
Reputation: 1346
If you don't use it it will be implied. So those two writes are equivalent in the compiled code because the compiler will add the this
.
The only problem that can occur is an ambiguity on a variable name. But as long as you use the convention of prefix (or postfix) member with m_
or _m
you should be safe.
Also you can see When should I make explicit use of the `this` pointer?
Upvotes: 0