[Exceptional C++ Style] Item 17 - Encapsulation

SamS at helpIT.com SamS at helpIT.com
Mon Dec 20 09:03:03 EST 2004


> As for remaining const. Again compared to what? The members _are_
> const. The question is how to "expose" them! Like this...
>
> class X_definition : public grammar_definition
> {
> public:
>     const non_terminal_definition if_statement;
> };
>
> or like this...
>
> class X_definition : public grammar_definition
> {
> public:
>     const non_terminal_definition & if_statement() const;
> };
>
> They're still const...

There is a difference in the degree of constness between the two. The first
promises complete constness, which means that the class is not assignable or
swappable, whereas the second one only prevents the client from modifying
the data element but doesn't promise that the value won't change from one
call to the next.

I have come across a number of situations where I had to re-consider the use
of const member data because the context where I wanted to use the class I
needed it to be assignable or swappable. As a result, I have become more
cautious about using const data members (and also reference data members).

Having said this I have to add that I see no reason why public const data
members would reduce encapsulation. It's just a slightly different
expression of intent.

Sam





More information about the Effective-cpp mailing list