Struct in C ++

Source: Internet
Author: User

Problem:
The C language contains the struct custom struct type;

There are also struct types in C ++, and they are very similar to the main Object-oriented Data Type class in C ++.

So what is the difference between struct and class in C ++, and under what circumstances should struct be used?

Solution:

The difference between struct and class in C ++ is summarized from the masterpiece C ++ programming language (Special Edition) by Bjarne Stroustrup, a C ++ language designer:

1. default access permissions of members. Struct members are public by default; class Members are private by default;

2. The default permission is inherited. If it is not explicitly specified, struct's default Inheritance Method is public, and class's default Inheritance Method is private;

3. The author believes that struct S {... is just a short form of class S {public.
4. However, the author's habit is to use struct to all classes whose members are public. In this case, "it is not a complete type, but a data structure ".

5. I am cautious about the suggestion that "class can be used for template parameters, while struct cannot be used for template parameters.

Because, as pointed out in C ++ programming language (Special Edition) 13.2, template <class C> only means that C is a type name and it does not have to be the name of a class.

The concept of a type name is more extensive than that of a class name. It includes not only the name of the class type introduced by the class definition, but also the internal type of the language, enumeration, and the name introduced by typedef.

 


Based on the above summary, I decided to use struct as a complex data structure in my own C ++ programming. Its members only contain member variables, does not contain member functions.

In this way, struct is closer to C in C ++, but struct in C ++ is more secure.

 


 

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.