Home > Article > Backend Development > Why is `const int operator[](const int index) const` preferred over `int operator[](const int index) const` for non-class types in C ?
The Significance of Returning Const for Non-Class Types
Question:
In C , why do we need to use const int operator[](const int index) const instead of int operator[](const int index) const?
Answer:
For non-class types, top-level const qualifiers on return types are ignored. This means that the return type of both:
int foo() {}
and
const int foo() {}
is interpreted as int. However, when returning a reference, the const becomes non-top-level and makes a significant difference:
int& operator[](int index);
and
int const& operator[](int index) const;
are distinct.
Similarly, for return values of class types, returning T const prevents the caller from calling non-const functions on the returned value:
class Test { public: void f(); void g() const; }; Test ff(); Test const gg(); ff().f(); // legal ff().g(); // legal gg().f(); // illegal gg().g(); // legal
The above is the detailed content of Why is `const int operator[](const int index) const` preferred over `int operator[](const int index) const` for non-class types in C ?. For more information, please follow other related articles on the PHP Chinese website!