dave5678
dave5678

Reputation: 20

What does the const keyword do in an operator definition?

I don't understand what the const keyword is used for in front of the return type and after the parameter list of this operator definition. This is taken from an example from a book.

const char& operator [] (int num) const
{
    if (num < getlength())
        return Buffer[num];
}

Upvotes: 0

Views: 69

Answers (2)

user439793
user439793

Reputation:

The C++ const keyword basically means "something cannot change, or cannot delegate operations that change onto other entities." This refers to a specific variable: either an arbitrary variable declaration, or implicitly to this in a member function.

The const before the function name is part of the return type:

const char&

This is a reference to a const char, meaning it is not possible to assign a new value to it:

foo[2] = 'q'; // error

The const at the end of the function definition means "this function cannot change this object and cannot call non-const functions on any object." In other words, invoking this function cannot change any state.

const char& operator [] (int num) const {
  this->modifySomething(); // error
  Buffer.modifySomething(); // error
  return Buffer[num];
}

The goal of const-correctness is a big topic, but the short version is being able to guarantee that immutable state actually is immutable. This helps with thread safety and helps the compiler optimize your code.

Upvotes: 3

Vladimir Voinea
Vladimir Voinea

Reputation: 1

It means the actual object you are calling this method on will not change, and if you attempt to change it, you'll get a compiler error.

Upvotes: 0

Related Questions