Const member function (GO)

Source: Internet
Author: User
Any function that does not modify a data member should be declared as a const type. If you inadvertently modify the data member when you write the const member function, or if you call other non-const member functions, the compiler will indicate the error, which will undoubtedly improve the robustness of the program. In the following program, the member function GetCount of a class stack is used only for counting, and logically getcount should be a const function. The compiler will indicate an error in the GetCount function. Classstack{public:void Push (int elem), int Pop (void), intgetcount (void) const,//const member function Private:intm_num;int m_data[ 100];}; int Stack::getcount (void) const{++ m_num;//Compile error, attempt to modify data member M_numpop ();//Compile error, attempt to invoke non-const function returnm_num;} The declaration of the Const member function looks strange: The const keyword can only be placed at the end of a function declaration, presumably because other places are already occupied.

Const member function (GO)

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.