Members of constant object of a class

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

 
foo.x = 20;


make sense?

Regards
Saher
Here this does not seems like an access from outside the class. The object is accessing its own data member.

1. Not sure what you mean by that. There is a difference between inside a class and an object accessing that class. In that example you could change the variable x whenever you wanted inside the class functions, however the object Const foo can't because it's "outside the class".

2. No. Const member variables can only be set once, and that is in the Initializer List in the constructor. If you want to learn more about those here are some links.

http://en.cppreference.com/w/cpp/language/initializer_list
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
Last edited on
O.K. Thanks for sharing the links.
Topic archived. No new replies allowed.