The differences between structs and classes in C + +

Source: Internet
Author: User

First from the language perspective, C language is a structured language, easy to organize programs in a modular way, easy to debug and maintenance of programmers, and for C + +, I can think of it as a standard C superset. In fact, all C programs are also C + + programs. But there is a small difference between the two.

Difference:

A structure is a combination of data in the C language, and C + + inherits the structure from C. In syntax, classes are similar to structs. On the relationship, the two are very close. In C + +, the role of the structure has been broadened. To a certain extent, the structure becomes a kind of substitution method. In fact, the only thing that is unique to a class and struct is that, by default, all members of a struct are public. And all members of the class are private. Besides. A class is equivalent to a struct, meaning that a struct defines the type of a class.

C + + contains both of these equivalent keywords, and the struct and class are based on 3 reasons. First: strengthening structural capacity. The structure in C simply provides a way to group data. Thus letting the struct contain member functions is a small improvement. Second, because classes and structs are interrelated. All of the current C code to C + + porting becomes easy. Thirdly, because of the equivalence of structure and class. Providing two different keywords allows the definition of a class to evolve freely, and in order to maintain C + + compatibility with C, the structure definition must always be terminated by its C definition.

Even if the structure can be used instead of the class in some places, try not to do so, for the sake of clarity, the class keyword is used where classes are changed, and the struct keyword is used where the C structure is instead. Do not impose the use.

The differences between structs and classes in C + +

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.