Question about struct vs class

Hello All,

I have question regarding the choice of struct vs class in some of the data structure.
Why the book has some data structures defined using struct like heap but some are defined as class like LinkedList. What is the reason behind it? I know basics of the difference between both but just curious to know why one vs the other in book?

Thanks in advance.

@kelvin_lau @jomoka Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hey!

There are various reasons why we chose to define the type as a struct or a class:

  1. If both definitions yield identical behavior, we preferred the struct definition.
  2. Some implementations can give free copy-on-write behavior (default behavior in STL). In those situations, we choose structs to get that for free.
  3. Recursive types must use classes or indirect enumerations. This is because recursive types have undefined size at compile time.

@prutha

Thanks very much for your question!

I simply wish to add a few points to help answer your question:

  1. Structs are value types, which means that they are stored on a Stack, whereas class objects are stored on a Heap. This means that struct objects are faster, and lightweight as compared to class objects.

  2. Struct objects are thread safe in a multi-threaded environment.

  3. Struct objects don’t come with the risk of memory leaks like class objects.

I hope this helps!

All the best.

1 Like

Technically speaking, structs and classes are almost equivalent, still there are many differences. The major difference like class provides the flexibility of combining data and methods (functions ) and it provides the re-usability called inheritance. Struct should typically be used for grouping data. The technical difference comes down to subtle issues about default visibility of members.

A short summary of each:

Classes Only:

  • Can support inheritance
  • Are reference (pointer) types
  • The reference can be null
  • Have memory overhead per new instance

Structs Only:

  • Cannot support inheritance
  • Are value types
  • Are passed by value (like integers)
  • Cannot have a null reference (unless Nullable is used)
  • Do not have a memory overhead per new instance - unless ‘boxed’

Both Classes and Structs:

  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces