When should I define a type as a struct or as a class?
I know that struct are value types while classes are reference types. So I wonder, for example, should I defin
Read "D"iving Into the D Programming Language
In D you get structs and then you get classes. They share many amenities but have different charters: structs are value types, whereas classes are meant for dynamic polymorphism and are accessed solely by reference. That way confusions, slicing-related bugs, and comments à la // No! Do NOT inherit! do not exist. When you design a type, you decide upfront whether it'll be a monomorphic value or a polymorphic reference. C++ famously allows defining ambiguous-gender types, but their use is rare, error-prone, and objectionable enough to warrant simply avoiding them by design.
For your Stack
type, you are probably best off defining an interface
first and then implementations thereof (using class
) so that you don't tie-in a particular implementation of your Stack
type to its interface.