From: Maciej Sobczak on
On 4 Kwi, 23:09, mtspark <markj...(a)gmail.com> wrote:

> I have an abstract interface, lets call it IAbstract with a single
> method, lets call it MethodA. Let's say this interface has two
> implementations, one for windows and one for linux.
>
> class IAbstract
> {
> public:
> virtual int MethodA() const = 0;
>
> };
>
> Is it correct to declare MethodA const as above?

Nobody knows, as the names of both the method and the whole interface
make it impossible to reason about the actual purpose of these
entities.

Assuming, however, that the operation is conceptually preserving the
logical state of the object (like, say, size() function of the
container), then yes, it is correct and even preferred to use const.

> My answer is that
> with c++ you cannot possibly know because you cannot predict what
> needs to be done within the two implementations.

No problem with that.

> In one implementation, Method A may just return a copy of the instance
> variable. Fine, const fits here. In another implementation, the
> underlying object state (perhaps another state variable) may have to
> change to get the answer. ie. The interface is logically const but the
> implementation is non-const. What should you do in this situation?

Use the 'mutable' keyword, perhaps?

This would be actually very good not only in that it would solve the
problem at the language level, but it would be actually self-
documenting. If you have a situation where there is an implementation-
level state that is changing even though the design-level state is
not, then that certainly deserves a spotlight.
The 'mutable' keyword is awful enough to attract the attention of the
code reviewer, which I would consider to be a *very* good thing in
this case.

> Adding const here violates the very principles of OO; encapsulation
> and information hiding.

No, none of these concepts is violated. On the contrary, these
concepts are perfectly preserved by using const - the fact that some
*implementation*-level state has to be modified is, well, an
implementation detail and can be hidden. The proper use of const/
mutable supports this design goal.

--
Maciej Sobczak * http://www.inspirel.com

YAMI4 - Messaging Solution for Distributed Systems
http://www.inspirel.com/yami4


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]