const methods
- C++ course
- Intermediate
- Lesson 26/116
- 5 min
Learn non-mutating access with const methods.
const methods
If you add const at the end of a member function's signature, that method cannot modify the object's member variables. This is called a const method. It gives the programmer and the compiler a promise: "this method does not change the object".
Example: int getArea() const { return width * height; }. With const, you cannot write width = 5; inside getArea; you get a compile error. Also, a const object can only call const methods. This is a C++ tradition called const correctness and documents the immutability guarantee explicitly in code.
const objects
If you declare an object as const, you can only call its const methods on it. If you write const Box b;, the call b.set(5) gives a compile error, because set can modify the object. But b.getArea() is allowed, because getArea is const.
This rule guarantees that constant objects truly stay unchanged. Making getters always const is a good habit: int getX() const { return x; }. This way they can be called on both const and non-const objects. Setters can never be const, because their purpose is to modify.
Practice Add a const method to the Box class
Define a Box class. Under private: add int width; and int height;. Under public: add void setSize(int w, int h) { width = w; height = h; } and int getArea() const { return width * height; }. In main create Box b;, call setSize(3, 4) and print getArea() with std::cout.
Starter code
#include <iostream>
// Define the Box class here
int main() {
// Create a Box instance, call setSize and print getArea
return 0;
}Sample solution
#include <iostream>
class Box {
int width;
int height;
public:
void setSize(int w, int h) {
width = w;
height = h;
}
int getArea() const {
return width * height;
}
};
int main() {
Box b;
b.setSize(3, 4);
std::cout << b.getArea();
return 0;
}Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each declaration to its role
| Term | Meaning |
|---|---|
int get() const |
Does not modify |
void set(int x) |
Can modify |
const Box b; |
Constant object |
b.get() |
Callable on const object |
2 Write the const keyword
int getArea() ____ { return width * height; }
int getArea() const { return width * height; }
Explanation: const states that the method will not modify the object.
3 After const Box b;, which can be called?
const Box b;- b.setWidth(5)
- b.width = 5
- b.area = 5
- b.getArea() Correct answer
Explanation: Only const methods can be called on a const object.