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?
I simply wish to add a few points to help answer your question:
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.
Struct objects are thread safe in a multi-threaded environment.
Struct objects don’t come with the risk of memory leaks like class objects.
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