Re: A::foo() or a.foo()
On Jan 31, 9:36 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
James Kanze wrote:
On Jan 30, 9:31 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
saneman wrote:
In A.h I have:
class A {
public:
std::list<int>l;
int foo();
...
...
};
In A.cpp I have:
int A::foo() {
return A::l.top(); // (1)
return l.top(); // (2)
return (this*).l.top(); // (3)
}
All 3 returns give the correct result (when used separately). But
which one is best to use or is it just a matter of taste?
The best is not to have 'l' public.
As to what form to use for accessing members, then in your
situation it is the matter of taste. All three are equivalent
from the language POV.
On the other hand, if a reader sees anything but (2), he's going
to wonder why?
Depends on the reader...
Have you ever seen a body of C++ code which used anything but
(2)? I'd pretty much say that (2) was "established practice",
and that anything else represents a special case. And
confronted with a special case, my first question would always
be: why didn't the programmer follow established practice.
The one exception would be in templates, where
this->l.top() might be used.
There is no reason in templates to use 'this->' to access your
own member.
Not your own member, but you need something to make the look-up
dependent when trying to access a member of a dependent base
class. The result is that there is an "established practice" of
using this-> in such cases, and it is not unreasonable to
imagine a programmer extending it to all member accesses in a
template.
It is, at any rate, the only convention other than (2) that I've
seen used at all.
The only reason I think the additional qualification or the
member access operator might be needed is to resolve the name
correctly if it's _hidden_ by another name in the scope:
If there is a dependent base class, using this-> forces
dependent name lookup. And it seems to be the most widely
spread idiom to force dependent name lookup in such cases.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34