Re: C++ Pitfall: const objects do not behave constantly.
On Sep 26, 10:59 am, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2007-09-26 06:27, Kira Yamato wrote:
[...]
#include <iostream>
struct Foo
{
int bar(int i) const
{
return i;
}
};
int main()
{
const Foo f;
std::cout << f.bar(1) << "\n";
std::cout << f.bar(2) << "\n";
}
By your reasoning both calls to bar() should return the
same thing, but that would be totally illogical.
Actually it is logical here. The object remains same state
here. So, everytime I invoke with 1 I get back 1; and
everytime I invoke 2 I get back 2 here. The singleton state
of this object dictates that the function bar be an identity
function on its input.
I can actually not see any difference between my example and
the one you gave, I have just moved the source of the
randomness from inside the function to outside. When it comes
to the object's state they are equal (in that the function's
results do not depend on the state of the object).
There's actually a very important difference, and Kira is
talking about an important concept (although it's not called
const, nor even constant): a pure function is one whose result
is entirely determined by its arguments (and the object a member
function is called on counts as an argument), and which modifies
no state (anywhere). There is no real support for pure
functions in C++. All a const function guarantees is that it
modifies no state of the object it is called on, and in
practice, what the state of the object consists of is defined by
the author of the class.
Your function is pure, his original function wasn't.
--
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