C++ const keyword.

Computer monitor showing C++ const keyword examples, including const parameters, const member functions, and combining both, placed on a wooden desk with a keyboard, mouse, and notepad.

TL;DR

const in C++ is a promise. Use it on parameters or functions to say, “I’m not changing this.” It makes your intent clear, prevents accidental changes, and improves code readability.


There are two main ways you can use const:

  1. const Parameters

If you have a parameter that you don’t intend to modify, mark it as const.

C++
void process(const std::string& text);

Here, text is read-only. If you try to modify it, the compiler will stop you. This is especially useful for references and pointers, where you could otherwise accidentally change the original object.

  1. const Member Functions

When you add const to the end of a member function, you’re telling the compiler that this function won’t change the object’s state.

C++
class Example {
public:
int getValue() const; // Won’t modify member variables
};

Inside such a function, this becomes a pointer to a const object, so you can only call other const member functions (unless a member is marked mutable).

  1. Combine multiple uses of const

You can make both the parameter and the function itself const:

C++
int compare(const Example& other) const;

Now neither this nor other can be modified in the function.

Why bother?

  • Makes your intent explicit.
  • Helps the compiler catch mistakes.
  • Makes your API easier to understand.

So this is something I’ll have to keep in mind moving forward with my C++ re-learning journey.

Leave a Reply

Your email address will not be published. Required fields are marked *