C ++ const-Class Object memo

Source: Internet
Author: User

I have always thought that the final keyword of Java is similar to the const keyword of C ++. Through more in-depth study of C ++, I gradually learned some of their differences.

1. The final of Java can modify the class. Although the const of C ++ can also be written in front of the class, it does not seem to work (not very sure)

 

2. c ++ protects const-modified class objects better than Java's final

Java:

Final classa A = new classa ();

A = B; // error: the constant cannot be modified on the left.

A. setvalue (10); // OK: it is acceptable to modify the member variables of object A. This is not very consistent with the original intention of using final.

A. getvalue (); // OK

 

C ++:

Const classc C ();

Classc D ();

C = D; // error: the constant cannot be modified on the left.

C. setvalue (10); // error: the setvalue method must be const, And the setvalue method cannot modify the member variables of Object C.

D. setvalue (10); // OK: whether the setvalue method is const or not, and the setvalue method can modify the member variables of Object D.

 

PS: classa and classc are Java and C ++ classes respectively. A, B, C, and D are class objects, and the setvalue method is used to change a member variable of these class objects.

 

The above shows that C ++ConstClass object,You can only call its constMethod,And the constThe method cannot modify member variables,This constThe method can beNon-constClass Object call.

 

A. setvalue (10) can be executed, while running C. setvalue (10) is incorrect. For a pair of comparisons, we can see that C ++ is better at protecting constant class objects than Java.

 

In the C ++ class, methods like getvalue can be modified with const, and inline is better.

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.