7

I have a property of a class, for example, const CFoo &bar() const, what does it mean?

cdmckay
  • 31,832
  • 25
  • 83
  • 114
domlao
  • 15,663
  • 34
  • 95
  • 134

3 Answers3

13

The method bar returns a reference to a const CFoo (that's the const CFoo & part before bar), and calling this method does not modify any variables that are not marked as mutable (that's the const after the parentheses).

See also the C++ FAQ Lite entries What does "Fred const& X" mean? and What is a "const member function"?.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
9
const CFoo& bar() const
----------      --------
      ^               ^
Returns a connst      None of the member variables of the class to which bar
reference of CFoo.    method belongs to can be modified.
                      unless member variable is prefexex with keyword mutable
aJ.
  • 34,624
  • 22
  • 86
  • 128
0

It's a const function (doesn't modify any non-mutable members of the object) member function that returns a reference to a const CFoo.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111