Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

15.4. Ensuring That a Member Function Doesn’t Modify Its Object

Problem

You need to invoke member functions on a const object, but your compiler is complaining that it can’t convert the type of object you are operating from const type to type.

Solution

Place the const keyword to the right of the member function declaration in both the class declaration and definition. Example 15-4 shows how to do this.

Example 15-4. Declaring a member function const

#include <iostream>
#include <string>

class RecordSet {
public:
   bool getFieldVal(int i, std::string& s) const;
   // ...
};

bool RecordSet::getFieldVal(int i, std::string& s) const {
   // In here, you can't modify any nonmutable data
   // members (see discussion)
}

void displayRecords(const RecordSet& rs) {
   // Here, you can only invoke const member functions
   // on rs
}

Discussion

Adding a trailing const to a member declaration and its definition forces the compiler to look more carefully at what that member’s body is doing to the object. const member functions are not allowed to invoke any nonconst operation on data members. If one does, compilation fails. For example, if, in RecordSet::getFieldVal, I updated a counter member, it wouldn’t compile (assume that getFieldCount_ is a member variable of RecordSet):

bool RecordSet::getFieldVal(int i, std::string& s) const {
   ++getFieldCount_;  // Error: const member function can't modify
                      // a member variable
   // ...
}

It can also help catch more subtle errors, similar to how const works in its variable-qualifier ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page