Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
A const member function is a type of
member function
that will not change the value of its class
members when called.
'A constant member function is a
function which may not modify
data members.' [11]
In class design, a
const member function reflects a read-only member function.
Exercise 5: the many types of const is an exercise about the many types of const.
Keeping a read-only method const using mutable
In a class, when you see the following member function:
You know it's a function that does not alter the member variables or the class.
But imagine that getting this value is a very time-intensive process. Then you might want the class to also store the amount of times this function has been called. Then you would use:
Although this is one of those occasions to use mutable, as every programmer expects a getter to be const:
- Bjarne Stroustrup. The C++ Programming Language (3rd edition). 1997. ISBN: 0-201-88954-4. Chapter 7.9.3: 'Use const extensively and consistently'
- Scott Meyers. Effective C++ (3rd edition). ISBN: 0-321-33487-6. Item 3: 'Use const whenever possible'
- Jarrod Hollingworth, Bob Swart, Mark Cashman, Paul Gustavson. Sams C++ Builder 6 Developer's Guide. ISBN: 0-672-32480-6. Chapter 3: 'Understand and use const in your code'
- Jesse Liberty. Sams teach yourself C++ in 24 hours. 2001. ISBN: 0-672-32224-2. Hour 8, chapter 'Const member functions': 'Use const whenever possible.'
- Scott Meyers. Effective C++ (3rd edition). ISBN: 0-321-33487-6. Item 2: 'Prefer consts, enums and inlines to #defines'
- Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 15: 'Use const proactively'
- Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Chapter 94: 'Avoid casting away const', item 'Exceptions'
- Scott Meyers. Effective C++ (3rd edition). ISBN: 0-321-33487-6. Item 3, paragraph 'Avoid duplication in const and non-const member functions'
- Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 16.4. Advice. page 479: '[6] Declare a member function that does not modify the state of its object const'
- Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 16.4. Advice. page 479: '[10] Make a member function that doesn't modify the value of an object a const member function'
- Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001 Rev C. December 2005. 4.3.9: 'A constant member function is a function which may not modify data members.'
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.
