Need for const functions

Hi,

Suppose I have a generic class

1
2
3
4
5
6
7
8
9
class Foo
{
private:
   int _member1;
   float _member2;
public:
   Foo(int m1, float m2) : _member1(m1), _member2(m2){}
   int get_m1() {return member1;}
}


If I declare a const object such as

const Foo myObject;

my understanding is that no member of myObject can be modified. Then why would I need a const function to deal with members of my const object? For instance, if I try to compile

1
2
3
4
5
6
7
8
9
int _tmain(int argc, _TCHAR* argv[])
{
   // a const object
   const Foo myObject(12,3.1416);
   myObject.get_m1();	

   system("pause");
   return 0;
}


I get an error C2662: 'Foo::get_m1' : cannot convert 'this' pointer from 'const Foo' to 'Foo &' unless I declare my get function as

 
 int get_m1() const {return member1;}


Could someone please explain what is the rationale behind this behaviour?

Cheers,
Little

Topic archived. No new replies allowed.