"trying_to_learn" <nospam@no.no> wrote in message
news:cn9hef$hno$1@gist.usc.edu...[color=blue]
> while seeing an example i was surprised to see that a const member
> function is allowed to change a static data member as shown below. I am
> trying to reason why.... and my guess is that static data members really
> dont belong to an object rather they belong to a class.
> however, isn't const a strict thing ? : where the compiler says "if u make
> this member function a const, i promise i wont let the function change the
> state of an object", yet it lets a const function change state of the
> object. why is this?[/color]
Static data members are not part of the state of any class instance.
They are more like global data that is encapsulated within the class,
for example to restrict access priviledges.
[color=blue]
> #include <iostream>
> using namespace std;
> class Obj {
> static int i, j;
> public:
> Obj() {}
> void f() const { cout << ++i << endl; }[/color]
The const applies to the state of the object on which f() is called.
As a static data member, 'i' does not belong to the object.
Consider the two additional members:
void foo(Obj& other) const;
void bar(const Obj& other);
In the body of foo and bar, when/why would constness be enforced
to the static data in Obj?
hth,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <>
http://www.brainbench.com