Home > Backend Development > C++ > body text

Why is `const int operator[](const int index) const` preferred over `int operator[](const int index) const` for non-class types in C ?

DDD
Release: 2024-10-30 13:26:35
Original
506 people have browsed it

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() {}
Copy after login

and

const int foo() {}
Copy after login

is interpreted as int. However, when returning a reference, the const becomes non-top-level and makes a significant difference:

int& operator[](int index);
Copy after login

and

int const& operator[](int index) const;
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!