c++novice wrote:[color=blue]
>[color=green]
> > object. Since it is declared constant (i.e., the second "const" in the
> > declaration), it cannot change the class object from which it is
> > called.[/color][/color]
Not 'from which' it is called.
*For which* it is called. The object you specify in the call
to this function, eg.
Calculator MyCalc;
MyCalc.GetStack();
[color=blue][color=green]
> >
> > Now, the reason I was puzzled by this is because the following code
> > (from a book I'm reading - I'm learning C++) does not compile unless
> > the second "const" is removed. So perhaps the book code is wrong? The
> > compiler doesn't like the assignment "_done = true;" in the context of
> > a const function. But shouldn't this be OK? I mean, it's only changing
> > an internal variable (to the same class) - i.e., it's not "changing
> > the class object from which it's called."[/color][/color]
It is attempting to change the class object.
But the const function has promised to not to do this.
[color=blue][color=green]
> >
> > class Calculator
> > {
> > public:
> > Calculator () : _done (false)
> > {
> > cout << "Calculator created\n";
> > }
> > bool Execute (Input & input)
> > {
> > cout << "Calculator::Execute\n";
> > return !_done;
> > }
> > IStack const & GetStack () const[/color][/color]
This function promises to not change the Calculater
object it is called with.
[color=blue][color=green]
> > {
> > _done = true;[/color][/color]
But here you try to exactly to do that.
[color=blue][color=green]
> > return _stack;
> > }[/color][/color]
If your main function looks eg. like this:
int main()
{
const Calculator MyCalc;
// here you have an object called MyCalc. You defined
// it to be const. This means that this object will
// not change during its whole lifetime.
//
// But now, you call
MyCalc.GetStack();
// you can do that. Function GetStack is marked as const,
// hence it will not change the MyCalc object in any way.
// And since this is so, it is legal to call that function
// on an object which is marked to not to change.
// But wait: inside GetStack the member variable _done
// if MyCalc gets changed! So the object has changed!
// But how can this be: GetStack has promised to not
// change MyCalc! But now MyCalc *has* changed.
That's why the copmiler will not allow you to compile the
function GetStack as it is now. If you declare that function
to be const, you are not allowed to change oridnary member
variables.
--
Karl Heinz Buchegger
kbuchegg@gascad.at