Table of Contents

C++ Const correctness

Const correctness means using const to document and enforce which functions and pointers should not modify their targets. A const member function promises not to modify the object, and a const parameter or reference promise the same to callers. This enables compiler checking and clarifies intent.

Apply const to all parameters and member functions that don't need to modify their targets for clarity and to enable passing const objects.

Example

This example shows const member functions and const references enforcing immutability.

// compile: g++ -o const const.cpp
// run: ./const
// description: const correctness prevents accidental mutations
 
#include <iostream>
#include <string>
 
class User {
private:
    std::string name;
public:
    User(const std::string& n) : name(n) {}
 
    const std::string& getName() const {
        return name;  // const function, const return
    }
 
    void updateName(const std::string& n) {
        name = n;  // non-const function
    }
};
 
int main() {
    const User u("Alice");
    std::cout << u.getName() << "\n";  // can call const methods
    // u.updateName("Bob");  // error: cannot call non-const on const object
 
    User u2("Charlie");
    u2.updateName("Dave");  // OK on non-const
    std::cout << u2.getName() << "\n";
 
    return 0;
}