this->field = value

T

TDH1978

I was browsing some of the Boost source code and noticed that,
occasionally, some of the libraries used the contruct:

this->field = value

inside a class member function definition, instead of just:

field = value


What is the benefit of using the first construct?
 
D

Donkey Hottie

I was browsing some of the Boost source code and noticed that,
occasionally, some of the libraries used the contruct:

this->field = value

inside a class member function definition, instead of just:

field = value


What is the benefit of using the first construct?

Readability and maybe less error prone that way.
 
A

Alf P. Steinbach

I was browsing some of the Boost source code and noticed that,
occasionally, some of the libraries used the contruct:

this->field = value

inside a class member function definition, instead of just:

field = value


What is the benefit of using the first construct?

* An editor with context-sensitive help (like Microsoft Intellisense)
can use "this->" as a clue to display a list of possible field names.

* In template code, if "field" is inherited from a base class that
depends on a template parameter, "this->" tells the compiler that
"field" is a member. A different fix is a "using" declaration.

* If you have a pedantic colleague who is good at following rules and at
requiring others to follow rules, and who is not good at understanding
any of the rules, and who has been unkind to someone who wrote "this->"
in contravention of some coding guideline or whatever, writing "this->",
and checking in the code with that colleague's user name, with the
knowledge that the colleague will later maintain this code, might feel good.


Cheers & hth.,

- Alf
 
S

Stefan Ram

TDH1978 said:
What is the benefit of using the first construct?

To me: Readability. The reader can immediatly see from this
that »field« is a field.

(Some programmers use an appended underscore to mark field
names, but this is not documented in C++, so it is not
checked by the compiler. When one uses »this->« it
unambigously marks fields and is checked by the compiler.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,139
Messages
2,570,806
Members
47,350
Latest member
Bsan

Latest Threads

Top