What is const correctness in C++?

  • const variables: const int max = 10;
  • const reference parameters: read without a copy.
  • const methods: promise not to change the object (int size() const).
  • const pointers: const int* (value const) and int* const (pointer const).
#include <iostream>
#include <string>

class User {
public:
    explicit User(std::string n) : name(std::move(n)) {}
    const std::string& get_name() const { return name; }     // does not change the object
    void rename(std::string n) { name = std::move(n); }       // changes it: not const
private:
    std::string name;
};

void print(const User& u) {          // can only call const methods
    std::cout << u.get_name() << '\n';
    // u.rename("x");                // error if enabled
}

int main() {
    User u("Riya");
    print(u);
}
Output

Riya

Also the keyword mutable lets a member change inside a const method (used for caches and mutexes). See Classes.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.