0Pricing
C++ Academy · Lesson

const Member Functions

Mark read-only methods.

What a const Member Function Is

A member function marked const promises not to modify the object's observable state. The keyword goes after the parameter list.

#include <iostream>

class Counter {
    int n = 0;
public:
    int value() const { return n; }   // read-only
    void inc() { ++n; }
};

int main() {
    Counter c;
    c.inc();
    std::cout << c.value() << "\n";
}

const Objects Call const Methods

On a const object you may only call const member functions. Non-const methods are forbidden.

#include <iostream>

class Counter {
    int n = 0;
public:
    int value() const { return n; }
    void inc() { ++n; }
};

int main() {
    const Counter c;
    std::cout << c.value() << "\n";   // OK
    // c.inc();                        // ERROR
}

All lessons in this course

  1. const Variables and Parameters
  2. const Member Functions
  3. constexpr and Compile-Time
  4. consteval and constinit
← Back to C++ Academy