Add a const after a class member function

Source: Internet
Author: User

When looking at the open source code, often see in the class member function after add const, before have not too concerned about, recently idle to have no matter, think of this matter, on-line check a bit, probably understand is how, here quoted Csdn 愽 paragraph words: "The compiler will automatically give each function plus a this pointer." After adding a const to a function of a class, it is indicated that the function cannot change the member variables of the class (except with the addition of the mutable modifier). In fact, that is, the this pointer is added a const modifier ". As an example:

Class Test

{

Public

Test (int a=10): AA (a) {}

~test () {}

int Geta () const {Aa++,bb++;return AA}

Private

int AA;

mutable int BB;

};

int main ()

{

Test T (100);

int cc = T.geta ();

};

Here the compiler will error, C2166: The lvalue Specifies the const object, the Geta () function cannot perform the aa++ operation, but it is possible to execute bb++.

Add a const after a class member function

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.