Home > Backend Development > C++ > body text

Why is `const int operator[](const int index) const` preferred over `int operator[](const int index) const` when returning objects?

Susan Sarandon
Release: 2024-10-31 19:54:02
Original
453 people have browsed it

Why is `const int operator[](const int index) const` preferred over `int operator[](const int index) const` when returning objects?

const Objects as Return Values: Beyond the Trivial

While it's widely accepted to use const in return types whenever possible, the question arises as to why const int operator[](const int index) const is preferred over int operator[](const int index) const. To delve into this, let's first explore the subtleties of const in return types.

As mentioned by "Effective C " Item 03, top-level const qualifiers on non-class return types are indeed ignored. Despite writing int const foo();, the return type remains int. However, this is not the case for reference return types. The difference between int& operator[](int index); and int const& operator[](int index) const; is crucial.

When returning class types, the const qualifier plays a significant role. If T const is returned, the caller is restricted from invoking non-const member functions on the returned object. Consider the following example:

<code class="cpp">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</code>
Copy after login

In this scenario, the const qualifier attached to gg() constrains the caller from accessing non-const member functions, such as f(), ensuring that the returned object's integrity is preserved.

Therefore, when returning const objects, the const qualifier on the return type serves a purpose beyond the trivial case of non-reference return types. It ensures that the caller interacts with the returned object in a consistent manner, preserving its internal state in accordance with the intent of the class design.

The above is the detailed content of Why is `const int operator[](const int index) const` preferred over `int operator[](const int index) const` when returning objects?. 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
Latest Articles by Author
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!