What overloaded version of the operator to call

Suppose I declared indexes in a class

  • char& operator[] (int index);
  • const char operator[](int index) const;

In what state is the second overload called. Is this called only through a const object .

In the following scenarios, the statement version will be called.

 const char res1 = nonConstObject[10]; nonConstObject[10]; 
+4
source share
2 answers

The first one is called. Do not confuse the return value; only arguments for choosing a method are considered. In this case, the implicit this not constant, so the non-constant version is called.

+13
source

Persistent methods can only be called from persistent instances. Since nonConstObject is not defined as const, both calls will be made using a non-constant overloaded operator.

-one
source

Source: https://habr.com/ru/post/1299354/


All Articles