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
- const Variables and Parameters
- const Member Functions
- constexpr and Compile-Time
- consteval and constinit