Topic 75 of 91 11. Additional C++ Topics Added Interactive Tutorial

The const Keyword in C++: Read-Only Variables, Parameters, and Members

9 mins read Last updated: 26 Sep 2026 18,275 views

Direct Answer & Core Concept

The const keyword creates read-only variables, prevents functions from modifying passed parameters (const T&), and guarantees that const member functions (void f() const) do not mutate object state, allowing compiler optimizations and eliminating subtle mutation bugs.

Detailed Explanation & Mechanics

1. Reading Pointers with Const (Clockwise/Spiral Rule):

  • 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).
Architecture Diagram
┌─────────────────────────┬──────────────────────┬──────────────────────┐
│ 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.

Runnable Code Example: The const Keyword in C++

C++20 / C++23
main.cpp
Run Online
#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;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is the `mutable` keyword used for in C++?

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

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.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

• Practice Const-Correctness: make every variable and member function const by default unless mutation is needed.
• 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.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.