Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which overloaded version of operator will be called

Suppose i have declared subscript operators in a class

  1. char& operator[] (int index);
  2. const char operator[](int index) const;

In what condition the second overload is called. Is it only called through a const object.

In the following scenarios which version of operator will be called.

const char res1 = nonConstObject[10]; 
nonConstObject[10];
like image 266
Yogesh Arora Avatar asked Dec 17 '22 03:12

Yogesh Arora


1 Answers

The first one is called. Don't get confused by the return value; only the arguments are considered to select the method. In this case, the implicit this is non-const, so the non-const version is called.

like image 144
fnieto - Fernando Nieto Avatar answered Dec 24 '22 00:12

fnieto - Fernando Nieto