I have two related questions to ask.
1)In the following link, it is written that
"When an object of a class is qualified as a const object:
The access to its data members from outside the class is restricted to read-only, as if all its data members were const for those accessing them from outside the class."
http://www.cplusplus.com/doc/tutorial/templates/
It then gives the following code example where a const object 'foo' is trying to change its own data member. However the code says that it is only allowed. Now i understand that a const object should remain unchanged but my confusion is that in the definition it says
"The access to its data members from outside the class is restricted to read-only"
Here this does not seems like an access from outside the class. The object is accessing its own data member. Should it not be allowed than according to the definition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
// constructor on const object
#include <iostream>
using namespace std;
class MyClass {
public:
int x;
MyClass(int val) : x(val) {}
int get() {return x;}
};
int main() {
const MyClass foo(10);
// foo.x = 20; // not valid: x cannot be modified
cout << foo.x << '\n'; // ok: data member x can be read
return 0;
}
|
2) I know that a constant member function can be called by const object of a class but can a const data member also be called by a const object?
Like If variable 'x' in the above example was a 'const int x', than, would
make sense?
Regards
Saher