Jump to content
  • Advertisement
Sign in to follow this  

const at the end of function

This topic is 5065 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
Const member functions can be called on const objects. They cannot modify non-mutable members.

class Foo
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;}


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

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!