franco ziade wrote:
what does this declaration mean in C++
void func_name() const
{ ... }
The const only really makes sense in member functions of classes. It
means that this class won't alter the state of the class. You should try
to mark all functions const which are const :)
For example, consider:
class S {
int i;
public:
int get() const { return i; }
void put(int j) { i=j; }
};
notice that I made get() const as it doesn't effect the state of the
class. Put is not const (and if you tried making it const it wouldn't
compile)
Now consider this function
void print(const S& s)
{ std::cout << s.get(); }
If get() wasn't const, this wouldn't compile, you you would be calling a
non-const member function on a const object.
One particular point of note is that you should be sure to make ==, !=,
<, and the other relational operators on classes const (assuming of
course they are), as many of the implementations of the standard
algorithms assume (and I believe they are allowed to assume) they can
put a const on things without effecting anything.
One final point. You can do:
public S
{
int i;
public:
int get() const {return i;}
int get() {i=0; return i;}
};
ie you can define the const and non-const version of a function
differently, and give them different meanings. You DON'T have to do this
just so non-const objects have a function (the const version can still
be used on non-const Ss).
Now different things will happen depending on is some instance of S is
const or not. Of course I've only ever seen someone write this once when
they weren't just messing about, and I was forced to kill them and bury
them under the patio so no other such code could ever escape. Don't make
me do the same thing to you!
Chris