Example 2:
Code:
#include <iostream>
class foo
{
public:
const foo& operator [] (int) const { std::cout << "Const operator called.\n"; return *this; }
};
int main()
{
foo bar1;
const foo& bar2 = bar1;
bar1[0];
bar2[0];
(bar1[0])[0];
(bar2[0])[0];
}
Output:
Const operator called.
Const operator called.
Const operator called.
Const operator called.
Const operator called.
Const operator called.
And example 3 won't compile:
Code:
#include <iostream>
class foo
{
public:
foo& operator [] (int) { std::cout << "Non-const operator called.\n"; return *this; }
};
int main()
{
foo bar1;
const foo& bar2 = bar1;
bar1[0];
bar2[0]; // <--- error here (object is const)
(bar1[0])[0];
(bar2[0])[0]; // <--- error here (object is const)
}