What is const overload?

Source: Internet
Author: User
When a query function has the same name as a change function and the number and type of parameters are the same, the difference between the two is that one has a const and the other has no Const.

A common application of const overload is the subscript operator. Generally, we should try to use standard template containers, such as STD: vector, but sometimes we need to support subscript operators in our own classes. An empirical rule is that subscript operators usually appear in pairs.

Class Fred {...};
Class myfredlist {
Public:
Const Fred & operator [] (unsigned index) const; operator subscript operator usually appears in pairs
Fred & operator [] (unsigned index); operator subscript operators are usually paired
...
};

When the subscript operator is used for a non-const myfredlist object, the compiler calls the non-const table operator. Because a normal Fred & is returned, the corresponding Fred object can be viewed or modified. For example, assume that the Fred class has a viewing function FRED: inspect () const and a change function FRED: mutate ():

Void F (myfredlist & A) except myfredlist is not const
{
// You can call a method without modifying the Fred object at a [3:
Fred x = A [3];
A [3]. Inspect ();
// You can call the method to modify the Fred object at a [3:
Fred y;
A [3] = y;
A [3]. mutate ();
}

However, when a const myfredlist object uses the subscript operator, the compiler calls the const subscript operator. Because const Fred & is returned, you can view the corresponding Fred object and cannot modify it.

void F (const myfredlist & A) When myfredlist is const
{< br> // you can call the method of the Fred object without modifying a [3:
Fred x = A [3];
A [3]. inspect ();
// error (lucky !): Try to change the Fred object from a [3]:
Fred y;
A [3] = y; fortunately, the compiler found this error during compilation.
A [3]. mutate (); the compiler is lucky to find this error during compilation.
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.