Home   Cover Cover Cover Cover
 

Classes versus Structs

Advantages of classes

  • Their objects are referenced through pointers and can therefore be linked into dynamic data structures such as lists, trees and graphs.
  • Objects of classes are not stored in the stack frame of the method that created them. If they are rooted in global variables the survive the method that created them.
  • In contrast to structs, classes can take advantage of inheritance and dynamic binding.

Advantages of structs

  • Their objects are not referenced through pointers. Accessing one of their fields does not require dereferencing a pointer. Therefore this access is more efficient than an access to a field of a class. Methods of structs are not called using dynamic binding (except interface methods). Therefore calling a method of a struct is usually more efficient than calling a method of a class.
  • Objects of a struct type are stored in the stack frame of the method in which they are declared. Their storage is automatically released when this method ends. Therefore they put no burden on the garbage collector.

Structs should be used for light-weight data types, which are used locally within a method and which are not linked into dynamic data structures. Classes, on the other hand, should be used for heavy-weight objects that should survive the method in which they were created. Objects of class types are also used if they need to be linked into dynamic data structures, if their classes should be extended, or if dynamically-bound method calls are required.