T
trying_to_learn
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?
#include <iostream>
using namespace std;
class Obj {
static int i, j;
public:
Obj() {}
void f() const { cout << ++i << endl; }
void g() const { cout << ++j << endl; }
};
int Obj::i = 47;
int Obj::j = 11;
int main()
{const Obj Obj1;
Obj1.f();
cin.get();
}
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?
#include <iostream>
using namespace std;
class Obj {
static int i, j;
public:
Obj() {}
void f() const { cout << ++i << endl; }
void g() const { cout << ++j << endl; }
};
int Obj::i = 47;
int Obj::j = 11;
int main()
{const Obj Obj1;
Obj1.f();
cin.get();
}