const at the end of function

Started by
3 comments, last by iMalc 19 years, 3 months ago
// 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...
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(); // OKf1.b(); // OKf2.a(); // Won't compilef2.b(); // OK
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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);
See this part of the C++ FAQ: "What is a const member function?"
- k2"Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ} | {Blog/Journal} | {[email=kkaitan at gmail dot com]e-mail me[/email]} | {excellent webhosting}
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.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement