The const Keyword in C++: Read-Only Variables, Parameters, and Members
What is The const Keyword in C++: Read-Only Variables, Parameters, and Members? The const keyword creates read-only variables, prevents functions from modifying passed parameters (const T&), and guarantees that const member functions (void...
How does const-correctness enforce immutability across variables, pointers, function parameters, and member functions?
Explanation & In-Depth Details
- `const int* ptr`: Pointer to a constant integer (cannot change `*ptr`, can change `ptr`).
- `int* const ptr`: Constant pointer to an integer (can change `*ptr`, cannot change `ptr`).
- `const int* const ptr`: Constant pointer to a constant integer (neither can change).
```text
┌─────────────────────────┬──────────────────────┬──────────────────────┐
│ Syntax │ Can Change Value? │ Can Change Address? │
├─────────────────────────┼──────────────────────┼──────────────────────┤
│ const int* p │ NO (*p is const) │ YES (p = &other) │
│ int* const p │ YES (*p = 10) │ NO (p is const) │
│ const int* const p │ NO │ NO │
└─────────────────────────┴──────────────────────┴──────────────────────┘
```
2. Const Member Functions:
Marking `void print() const` guarantees that the method can be safely called on `const` object instances.
Code Example
#include <iostream>
#include <string>
class DatabaseConnection {
private:
std::string hostName;
int port;
public:
DatabaseConnection(std::string host, int p) : hostName(std::move(host)), port(p) {}
// Const member function: does NOT mutate object
void displayConnection() const {
std::cout << "Connected to: " << hostName << ":" << port << "\n";
}
// Non-const member function
void setPort(int newPort) {
port = newPort;
}
};
// Function taking const reference to avoid expensive copy and accidental mutation
void auditConnection(const DatabaseConnection& db) {
db.displayConnection(); // Allowed (const method)
// db.setPort(9000); // COMPILE ERROR: db is const reference!
}
int main() {
const int MAX_USERS = 5000; // Immutable constant
DatabaseConnection liveDb("cluster.operate.tools", 5432);
auditConnection(liveDb);
return 0;
}Interview Question & Tips
A: `mutable` allows a specific member variable of a class to be modified even inside a `const` member function (frequently used for caching, mutexes, or internal audit counters).
Q: Why should function arguments be passed as `const T&` instead of `T`?
A: Passing by `const T&` avoids the performance cost of deep-copying large objects while protecting the original object from unintentional modification.
Best Practices
• Pass non-primitive parameters by `const T&` to eliminate unnecessary copy construction.
• Use `const_cast` only as an absolute last resort when integrating with legacy C APIs that lack const annotations.
This study reference for The const Keyword in C++: Read-Only Variables, Parameters, and Members is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: