Re: const and ABCs
seanf wrote:
Hi group
Should I ever declare pure virtual functions const in an ABC?
A simple test for logical constness should decide whether a pure
virtual method (or any virtual method) should be declared const or not.
The test is simply whether calling the method changes the object in a
"client-observable" way. If it is not possible for the client to detect
any change after calling a certain method, then that method is a const
method. Otherwise it is not. For example, say the class has an Init()
and GetID() methods. If the class's interface permits GetID() to return
0 - unless Init() has been called on that object - then calling Init()
results in an observable change to the object (GetID() returns a
different value before the call than afterwards). Init() should
therefore be declared a non-const method. As it may seem evident, most
virtual class methods will in all likelihood be non-const.
On the other hand, if I don't, I can end up with embarrassingly
non-const getName() and the like in an otherwise const-correct
implementation class.
So the question here is whether calling GetName() allows any method in
the public interface (including GetName() itself) to return a different
result than that method would have returned, had GetName() not been
called. If the interface grants any method such permission, then
GetName() is not const.
Note that a non-const GetName() method would be unusual. And it would
likely make clients of the interface a litle queasy. Because the
interface is essentially informing clients that a call to GetName()
could change the object in some observable way, But the client is
likely to have little idea exactly what kind change that could be or
whether the change would be a welcome one.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]