C++: const

const is trick to begin with ...

this is what I found while working with it ...

1. References: They cannot be changed to point to some other object
2. Pointers: Can be changed to point to something else

1 class Foo {
2 int i;
3 public:
4
5 void doit (const Foo &that) {
6 that.i = i; //Error
7 }
8 void doit (Foo &that) {
9 that.i = i; //Okay
10 }
11 void doit (const Foo *that) {
12 that->i = i; //Error
13 that = this; //Okay
14 }
15 void doit (Foo * const that) {
16 that->i = i; //Okay
17 that = this; //Error
18 }
19 void doit (const Foo &that) {
20 i = that.i; //Okay
21 }
22 void doit (const Foo &that) const {
23 i = that.i; //Error
24 }
19 };

--Sorry about the alignment, I dont know a way as of now to correct this ... I guess it is readable though ! If someone already knows, let me know (how to preserve the formatting like we do in wiki)

test2.cpp: In member function `void Foo::doit(const Foo&)':
test2.cpp:6: error: assignment of data-member `Foo::i' in read-only structure
test2.cpp: In member function `void Foo::doit(const Foo*)':
test2.cpp:12: error: assignment of data-member `Foo::i' in read-only structure
test2.cpp: In member function `void Foo::doit(Foo*)':
test2.cpp:17: error: assignment of read-only parameter `that'
test2.cpp: In member function `void Foo::doit(const Foo&) const':
test2.cpp:23: error: assignment of data-member `Foo::i' in read-only structure

Observations:
1. There is no question of changing a reference ... But in the first and second doit definitions we can see that if its a reference to a const object, we cant change it

2. In third and fourth definitions we can note that in const Foo *, we could change the pointer itself, whereas in Foo * const we could change the values.... So the way to read it is anything before the * tells about the characteristics of object and anything after the * tells about the characteristics of the pointer

3. In fifth and sixth, const tells that you cannot change the object pointed to by this (the implicit parameter)

I hope it makes sense..

Comments

Popular posts from this blog

Arvin.cpp

Living with Equanimity