|
-
September 5th, 2010, 07:33 AM
#1
can't understand const function's output
Hi.
Please tell me what will be the correct output for this code:
class A {
public:
int & _i;
A();
void foo() const;
};
A::A(int& i) : _i(i) { ... }
void A::foo() const {
_i++;
}
With this main:
int main() {
int i = 5;
const A a (i);
std::cout << a._i << std::endl;
a.foo();
std::cout << a._i << std::endl;
}
Can _i be changed? Isn't it the meaning of const func - that
all class' members can't be changed by it ?
-
September 5th, 2010, 07:57 AM
#2
Re: can't understand const function's output
The members of the class cannot be changed. However, you aren't changing A::_i; it still references the same thing after the call as before (in fact, it is impossible to change what a reference points to, so all references are effectively const anyway). The key is that although you cannot change the part of memory that the reference is pointing at, you *can* change what is in that memory; this doesn't violate const-ness in this case. (It is possible to use the const keyword differently if you don't want this to be possible.)
It's easier to explain with pointers, since they have a possibilty of being themselves modified unlike references:
Code:
int i = 0;
int k = 1;
int * const icptr = &i;
const int *ciptr = &i;
const int * const cicptr = &i;
*icptr = 2; // legal, modify i
icptr = &k; // illegal, cannot reassign icptr
*ciptr = 3; // illegal, cannot modify i
ciptr = &k; // legal, can point ciptr somewhere else
*cicptr = 4; // illegal, cannot modify i
cicptr = &k; // illegal, cannot reassign cicptr
-
September 5th, 2010, 08:13 AM
#3
Re: can't understand const function's output
Thank you very much!
Just let me get this straight:
1. a reference is a kind of const pointer
2. doesn't need dereference, it changes the value behind the pointer
3. you can't access data "around" its location in memory (like ++pointer).
right?
-
September 5th, 2010, 09:19 AM
#4
Re: can't understand const function's output
Essentially correct. References are pretty much just a bit of syntactic sugar on top of pointers. The major difference is that (a) pointers can be NULL while references cannot, and (b) references cannot be reassigned to point to something else once created.
In fact, since the above struct has a reference member, you should be getting a compiler warning that it is unable to generate a copy constructor for that type. This is a result of this limitation, and why pointers are often used in place of references for such structs.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|