No, you can't do that; in a const
method you have a const
this
pointer (in your case it would be a const Foo *
), which means that any reference you can get to its fields1 will be a const
reference, since you're accessing them through a "const
path".
Thus, if you try to do what you did in that code you'll get a compilation error, since you'd be trying to initialize an int &
(the return value of your method) with a const int &
(the reference you get from Bar
), which obviously is forbidden.
g++ actually says:
testconstref.cpp: In member function ‘int& Foo::GetBar() const’:
testconstref.cpp:9: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘const int*’
which is what I just said. :)
If, instead, you return a const
reference to a class field from a const
method you'll have no problem.
- Excluding fields marked as
mutable
, which tells to the compiler that such fields are modifiable even from const
methods; this exception has been introduced to allow const
methods to change the "real" state of the object in cases when this do not alter its "logical" state; this can be useful to implement lazy evaluation, reference counting, ...
&Bar
has typeconst int*
, notint&
. You compiler should be telling you that this is not OK.