Tech News

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

  • If you don’t specify public: or private:, members of a struct are public by default; members of a class are private by default. Struct and class are otherwise functionally equivalent.
  • C has structs, it has no concept of 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  which was the idea in C++ (originally “C With Classes”), it makes sense to make members private by default.So a new keyword, class was introduced to be exactly like a struct, but private by default.

  • STRUCT is a type of Abstract Data Type that divides up a given chunk of memory according to the structure specification. Structs are particularly useful in file serialization/deserialization as the structure can often be written to the file verbatim. (i.e. Obtain a pointer to the struct, use the SIZE macro to compute the number of bytes to copy, then move the data in or out of the struct.)
    Classes are a different type of abstract data type that attempt to ensure information hiding. Internally, there can be a variety of machinations, methods, temp variables, state variables. etc. that are all used to present a consistent API to any code which wishes to use the class.
    However, you do need to understand that these are merely abstractions. It’s perfectly possible to create structs that look a lot like classes and classes that look a lot like structs. In fact, the earliest C++ compilers were merely pre-compilers that translates C++ code to C. Thus these abstractions are a benefit to logical thinking, not necessarily an asset to the computer itself.
  •  There is no term like constructor and destructor for structs, but for class compiler creates default if you don’t provide.if you do not define a constructor in a class, the compiler will define one. but in a struct if you do not define a constructor, the compiler do not define a constructor too. so in some cases that we really do not need a constructor, struct is a better choice (performance tip). 
  • Sizeof empty structure is 0 Bytes wer as Sizeof empty class is 1 Byte The struct default access type is public. A struct should typically be used for grouping data.A structure couldn’t be null like a class.
  • Classes can be inherited whereas structures not.
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x