• Advertisement
Sign in to follow this  

const at the end of function

This topic is 4794 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

// Array subscripting.
Real &operator[](int i);
const Real &operator[](int i) const;
Lately I've been seeing this use alot and have been wondering what does the const at the end of the function means? I got this code from a Matrix class library and was wondering...

Share this post


Link to post
Share on other sites
Advertisement
Const member functions can be called on const objects. They cannot modify non-mutable members.

class Foo
{
public:
void a();
void b() const;
};

Foo f1;
const Foo f2;

f1.a(); // OK
f1.b(); // OK
f2.a(); // Won't compile
f2.b(); // OK

Share this post


Link to post
Share on other sites
Are you sure that's right Fruny? I thought that a const function was just one that didn't alter it's object; irrespective of whether it's a const object.

That's why you can write accessors as:

int GetData() const {return data;}

Jim.

Edit : nope, you're right, your example doesn't compile. I guess it's an aspect I hadn't considered (and my example falls within your example anyway, as f1.b);

Share this post


Link to post
Share on other sites
My understanding is this:
a non-static class member function has an implicit 'this' parameter.
So a function in 'myclass' defined as
int myclass::foobar(int &x)
is compiled as if it were like this
int foobar(myclass *this, int &x)
Now say you wanted to make 'x' constant you would write it like this:
int myclass::foobar(const int &x)
But what if you wanted to make the implicit 'this' pointer const? Well, that is exactly what putting const on the end does!
Effectively this:
int foobar(const myclass *this, int &x)


I hope that makes sense.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement