The difference between structure and class

Possible duplicate:
What are the differences between structure and class in C ++

I did my homework and had different answers on Google. Some say that structures do not have inheritance, some say that structures do not have access qualifiers, while others say that they have both. Can someone clarify then the differences between structure and class in C and C ++, as well as the difference between structure in C and C ++.

+7
source share
2 answers

In C ++, the only difference between a structure and a class is that the members of the structure are public by default, and the members of the class are private by default.

However, as a style, it is best to use the struct keyword for something that can be reasonably structured in C (more or less POD types) and the class keyword if it uses C ++ - specific functions such as inheritance and functions - members.

C has no classes.

C structs cannot use C ++ special functions.

EDIT

The C ++ FAQ Lite , question 7.9, has this to say:

The elements and base classes of a struct are public by default and class are private by default. Note: you should make your base classes explicitly public , private or protected , rather than relying on the default values.

struct and class are otherwise functionally equivalent.

Well, enough of this creaky clean techno talk. Emotionally, most developers make a strong distinction between class and a struct . A struct just feels like an open bunch of bits with very little bits in the way of encapsulation or functionality. A class feels like a living and responsible member of a community with intelligent services, a strong sealing barrier and a well-defined interface. since in the connotation that most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things exist in well-designed systems!), but otherwise case, you should probably use the class keyword.

And quoting Stroustrup "C ++ Programming Language", 4th edition, section 16.2.4:

These two definitions of S are interchangeable, although it is usually wise to stick to one style. Which style you use depends on the circumstances and taste. I usually use struct for classes, which I think of as “just simple data structures”. If I think of a class as the correct type with an invariant: "I use a class . Constructors and access functions can be very useful even for * struct * s, but as a shorthand, not as guarantors of invariants.

+22
source

Classes do not exist in C. In C ++, structures have a default access specifier of public , and classes by default are private .

There are several differences between C and C ++ structures; in C ++, they can inherit from other classes or structures, they can contain member functions, and their names should not be mentioned with a specified type specifier.

+3
source

All Articles