// 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...
const at the end of function
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
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);
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);
My understanding is this:
a non-static class member function has an implicit 'this' parameter.
So a function in 'myclass' defined as
Effectively this:
I hope that makes sense.
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 thisint 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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement