member functions for const-decorated classes

Source: Internet
Author: User



"Effective C + +" Inside said, as far as possible to use CONST,CONST modified variable generally there are two ways: const T *a, or T const *a, both are the same, mainly see the const is located on the left or right, here no longer repeat, Let's take a look at the member functions of the const-decorated class, what are the characteristics of the member function.


the member function of the class is followed by a const,indicates that this function does not make any changes to the data members of this class object (accurately, non-static data members).

when designing a class, one principle is to add a const to the member function that does not change the data member, and the member function that changes the data member cannot be const. Therefore, the Const keyword defines the behavior of the member function more explicitly:a const-Modified member function (that is, the const is placed after the function parameter table, not in front of the function or in the parameter table), can only read the data member, cannot change the data member, the member function without the const adornment, the data member is readable and writable.

Besides, what is the benefit of adding a const after the member function of a class? that is, a constant (that is, a const) object can call a const member function, not a non-const-decorated function.


Note: Two member functions can be overloaded if they are just a constant

For example:

Class A

{

Public

void F ()

    {

cout<< "Non const" <<endl;

}

void f () const

    {

cout<< "Const" <<endl;

}

};

Microsoft written The second question is exactly this, the const object calls F () const, non-const object call F ()


member functions for const-decorated classes

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.