The differences between structs and classes in C + +

Source: Internet
Author: User

In C + +, a struct is a special form of a class.

The only difference between structs and classes is that structs and classes have different default access control properties .

  class , the access control property for a member that does not specify an access control property is a private type (private)

  struct , the access control property for a member that does not specify any access control properties is public type

in C + +, the inability to use structs does not affect the ability of the program to express . C + + is introduced to the structure to maintain compatibility with C programs.

However, structs are still used in C + + because structs can be used to compose different types of data to make it easier to save data. (If you save with a class, it is cumbersome to read and overwrite individual properties for each data member-specific function because the members of the class are private by default.) )

Structs in C are not allowed to define function members, and there is no concept of access control properties.

C + + introduces the object-oriented features such as member functions, access control permissions, inheritance, polymorphism, and so on, in C language structure.

C + + introduces the class keyword outside of the struct, but in order to maintain compatibility with the C program, C + + retains the struct keyword and specifies that the struct's default access control permissions are public types.

In addition,in C, the size of the empty struct is 0, while the C + + hollow struct (which belongs to the empty Class) is 1.

The reason for the size of the empty class in C + + is 1:

An empty class can also be instantiated, and each object instantiated by the class needs to have a different memory address, so that each object has a different address in memory, so an implied byte is added to the class.

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.