0
0
CppConceptBeginner · 3 min read

What is const member function in C++: Explanation and Example

A const member function in C++ is a function that promises not to change the object's state. It is declared by adding const after the function signature, ensuring it cannot modify any member variables or call non-const functions.
⚙️

How It Works

Imagine you have a book that you want to read but not write in. A const member function is like a rule that says, "You can look at the pages, but you cannot write or change anything." In C++, when you add const after a member function, you tell the compiler that this function will not change the object's data.

This means inside that function, you cannot modify any member variables or call other functions that might change the object. The compiler enforces this rule, so if you try to change something, it will give an error. This helps keep your code safe and clear about which functions only read data and which can modify it.

💻

Example

This example shows a class with a const member function that returns the value of a member variable without changing it.

cpp
#include <iostream>
class Box {
private:
    int length;
public:
    Box(int l) : length(l) {}
    int getLength() const {
        return length; // Just reading, no change
    }
    void setLength(int l) {
        length = l; // This changes the object
    }
};

int main() {
    Box box(10);
    std::cout << "Length: " << box.getLength() << "\n";
    box.setLength(20);
    std::cout << "New Length: " << box.getLength() << "\n";
    return 0;
}
Output
Length: 10 New Length: 20
🎯

When to Use

Use const member functions when you want to guarantee that calling a function will not change the object. This is especially useful for functions that only provide information, like getters or display functions.

In real life, this is like checking the temperature on a thermometer without changing it. Marking functions as const helps other programmers understand your code better and prevents accidental changes to important data.

Key Points

  • A const member function cannot modify any member variables.
  • It can be called on const objects or references.
  • Helps enforce read-only access to object data.
  • Improves code safety and clarity.

Key Takeaways

A const member function promises not to change the object's data.
Use const member functions for read-only operations like getters.
The compiler enforces const correctness to prevent accidental changes.
Const member functions can be called on const objects.
Marking functions const improves code safety and readability.