When accessing a member of some class, I can use e.g.:
this->myVar = 10
or I can just write:
myVar = 10
I like to use this->
because it explicitly declares that the variable is a member of this class, but does it cause any overhead in comparison to just using the variable name by itself?
As an alternative I could maybe add a unique prefix to the vars, such as _TmyVar
, but I've been using this->
for a long time so I just wondered.
I sometimes uses explicit this-> in setters, since they allow me to use the same name for the parameter names as the instance fields:
however, in constructors, I usually use initialization list, which does not require an explicit this->
Those two lines of code have the same meaning. The
this->
is implicit in the second line. They do exactly the same thing.Thus, they perform exactly the same as well :-)
There is no overhead. The compiler will generate the exact same code for both versions.
Yes, it's more to write, and more to read, and indicates to readers of the code that it was written by someone not familiar with C++, so that they have to use extra time on carefully checking everything. All of that is programmers' overhead. It costs money.
There is, however, no overhead of the kind that generally doesn't cost anything, efficiency of generated machine code.
Summing up, there is overhead of the costly kind, and none of the cheap/free kind.
Names of the form
_TmyVar
, starting with underscore followed by uppercase letter, are reserved for the implementation.Don't do that.
The two most common C++ naming conventions for non-static data members are
myVar
(prefixmy
) andvar_
(suffix_
).Cheers & hth.,
There is no difference in meaning (unless there's more than one name
myVar
visible, in which case the ordinary version could mean a function-local variable whilethis->myVar
means a member). So yes, it's just a matter of style.