Differences in const in function declarations

If a function is declared as

virtual const string toString() const;

what do each of the const declarations do?
The first one means "a constant string". The second one means "the function may used with constant this arguments (and therefore can't modify its members)".
When does using this become constant? Also, should const be used in the return value only when the value return is a literal?
Last edited on
1
2
const T object;
T.function(); //if function() isn't const, this gives a compiler error 
Last edited on
I was wondering if this function's return value should be declared const.

1
2
3
4
5
string Object::toString() const {
	stringstream string_stream;
	string_stream << this;
	return string_stream.str();
}


I'm trying to experiment with returning a const value, and trying to throw a run-time error, but I can't seem to do so. I've tried returning "test", and then doing object.toString[1] = '1', but it ran just fine.
Last edited on
Yes, it should be const as long as operator<< does not modify Object (which it shouldn't; I say that on the general principle that output of some data shouldn't modify the data).
Topic archived. No new replies allowed.