Const vs Non-Const Functions in C++
In C++, member functions of a class can be marked as const to indicate that they do not modify the object’s data members. This helps protect data and lets the compiler catch errors if you accidentally try to change something in a function that shouldn't.
A non-const function can modify the object’s data members. It is the default type of function if you don’t add const after the function declaration.
class Box {
private:
int length;
public:
void setLength(int l) {
length = l; // Can modify data
}
};
A const member function cannot change any data members of the class. It is declared by adding const after the function parentheses.
return_type function_name() const
class Box {
private:
int length;
public:
int getLength() const {
// length = 10; ❌ Not allowed, will cause error
return length;
}
};
In this example, getLength() is a const function, so it cannot change the value of length.
You must use const functions if you're calling them on a const object.
const Box b1;
b1.getLength(); // ✔ Allowed only if getLength() is a const function
If getLength() is not const, it will give a compiler error.
| Feature | Const Function | Non-Const Function |
|---|---|---|
| Modifies object data | No | Yes |
| Can be called by const object | Yes | No |
| Syntax | function() const |
function() |
Using const with functions helps write safer, more reliable code, especially when working with large classes or sharing objects across different parts of a program.
Open this section to load past papers