What are the differences between struct and class in C++?

后端 未结 30 3208
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:38

This question was already asked in the context of C#/.Net.

Now I\'d like to learn the differences between a struct and a class in C++. Please discuss the technical d

30条回答
  •  别那么骄傲
    2020-11-21 05:59

    It's worth remembering C++'s origins in, and compatibility with, C.

    C has structs, it has no concept of encapsulation, so everything is public.

    Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.

    On the other hand, if Stroustrup had changed the semantics of struct so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).

    So a new keyword, class was introduced to be exactly like a struct, but private by default.

    If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.

    In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you can have constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.

提交回复
热议问题