Constant declaration in function

can somebody tell me the difference between:

const int testFunction() &
int testFunction() const
1
2
3
void foo::function() const;
//equivalent to
void function(const foo *this);
ne555 can you elaborate, I mean a descritption of what the function is doing is appreciated.
Not having the function body, it's impossible to say what the function is doing.

The const on void foo::function() const tells the compiler and any users of the class that this function doesn't modify the object it operates on.

It means:
1
2
3
4
5
6
7
8
int main()
{
    foo f ;
    int x = f.function() ;   // foo will not be modified here

    const foo g ;
    int y = g.function() ; // if the function were not const, this would not be legal.
}


1
2
3
4
int foo::function() const
{
    some_member = some_value ; // illegal unless some_member is mutable.
}


Whereas const int testFunction() means the function returns an int that cannot be modified, which is redundant since the returned object is a temporary one.
Topic archived. No new replies allowed.