const Correctness
Prerequisites: Multiple inheritance
Marking a member function const (seen already on getBalance()
and area() in earlier lessons) promises it won't modify the
object — the compiler enforces this, and only a const method can
be called on a const object or reference.
class Point {
private:
int x, y;
public:
Point(int x, int y) : x(x), y(y) {}
int getX() const { return x; } // doesn't modify — const
void setX(int newX) { x = newX; } // modifies — not const
};
void printPoint(const Point &p) {
std::cout << p.getX() << std::endl; // fine — getX is const
// p.setX(5); // would NOT compile — p is a const reference
}
Passing large objects as const & (rather than by value) is the
default in idiomatic C++ — no copy is made, and const guarantees
the function can't accidentally modify the caller's object.
Common mistakes
- Passing an object by value out of habit when
const &would avoid an unnecessary copy — for anything larger than a couple of primitives, preferconst &.