Loading lessons...
Const Class Objects and Const Member Functions
Const Class Objects and Const Member Functions
Declare an object as const and it becomes read-only: it cannot be changed after you build it. To match that promise, const objects may only call const member functions - methods that promise not to modify the object.
A const object
const Car myCar; // read-only object
cout << myCar.getYear(); // OK only if getYear() is const
Trying to call a non-const method on a const object fails at compile time.
A const member function
Write const after the parameter list:
class Car {
int year;
public:
int getYear() const { // const function
return year;
}
void setYear(int y) { year = y; } // not const
};
- The
constguarantees the method will not modify the object. - A const method can read members but cannot write them.
Why the rule exists
- Compiler catches mistakes at build time instead of runtime.
constdocuments intent: the call cannot change anything.- Const references can be passed safely everywhere without fear of mutation.
TL;DR
- A const object is read-only after construction.
- Const objects may only call const methods.
- Mark a function const with
void print() const;. - A const method promises it will never modify the object.