C++
const methods
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.
Exercise 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.
Show example 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;
}
Test yourself
-
Match each declaration to its role
- int get() const
- Does not modify
- void set(int x)
- Can modify
- const Box b;
- Constant object
- b.get()
- Callable on const object
-
Write the const keyword
int getArea() ____ { return width * height; }
Show answer
int getArea() const { return width * height; }
-
After const Box b;, which can be called?
const Box b;
- b.setWidth(5)
- b.width = 5
- b.area = 5
- b.getArea()
Show answer
b.getArea() — Only const methods can be called on a const object.
Next lesson: mutable