[Exceptional C++ Style] Fw: const data - was Item 17
Adrian Fagg
adrianf at evaluategroup.com
Tue Dec 21 07:14:20 EST 2004
> -----Original Message-----
> From: effective-cpp-bounces at accu.org
> [mailto:effective-cpp-bounces at accu.org]On Behalf Of Balog Pal
> Sent: 20 December 2004 20:47
> Most of the item stuff you fing in gotw#70
> http://www.gotw.ca/gotw/070.htm
>
> // Example 2(a): Nonprivate data (evil)
> //
> class X
> {
> // ...
> public:
> T1 t1_;
> protected:
> T2 t2_;
> };
>
>
>
> // Example 2(b): Encapsulated data (good)
> //
> class X
> {
> // ...
> public:
> T1& UseT1() { return t1_; }
> protected:
> T2& UseT2() { return t2_; }
> private:
> T1 t1_;
> T2 t2_;
> };
I'm rather stunned by this. I suppose that this non-const reference return
could be justified for some tiny set of cases - sort of advanced structs or
something, but it seems like a pretty tendentious example of encapsulation
to me.
Languages with properties allow for this kind of progression quite naturally
but for C++ this only really works for overloaded index operators.
i.e. to me it seems natural as well as safely extendable to write:
x[89] = 7;
but anti-idiomatic to write
x.MyProp() = 100;
why not support the style:
if(x.MyProp() < 100)
x.MyProp(100);
or variations.
And re the GotW above, I'm not completely convinced by the argument that
polymorphism is a form of encapsulation. I mean, OK it usually is in
practice and from the point of view of the caller of a virtual function,
they aren't using the internals directly. As for compile time polymorphism,
well, it could be working directly with a common set of internals in
structs.
A weekend back, I was walking across some fields with a friend, mainly to
get some miles in with a heavy rucksack, when we came to a style as it was
getting dark. My friend clambered over it, while I walked round where the
fence used to be. You can have a struct with virtual functions if you must!
Regards,
Adrian
Work: mailto:adrianf at evaluategroup.com
Home: mailto:adrian.fagg at ntlworld.com
Pretty pictures: http://homepage.ntlworld.com/rbyadf/
More information about the Effective-cpp
mailing list