The classes and structs have one difference between them (as far as I know), that the struct defaults to public and class defaults to private. And then I came to know that there is a similar kind of data type which is also used in a similar manner, that is union. The union can not be used as a base class in inheritance (i don’t know what that means, but I still accept it).
I wanted to know whether there are some particular instances, where struct/ union/ class, or they can be used interchangeably (except for the cases I enlisted)? Please do tell me if I am wrong somewhere.
Regards
My use of
class,structandunionis the following:classfor objects that have behaviour.structfor passive data.unionfor very special cases where different data requires to be accessed as different types.I’ve read this (except the
unionpoint) in the Google C++ Style guide a long time ago and I was following it since then.Using
structs to carry passive data (objects without behaviour attached to the object) have the advantage of default publicness of the members, so they can be accessed without Getters and Setters. If some member data needs to be checked/modified before assign or some member data needs to be computed/modified before be getted, IMHO they need a Setter/Getter pair and the object is aclassinstead of astruct.For the
uniontype, I find it useful for some kind of data structures that requires some weird access to the members, or needs some members to be treated as another type in some contexts. For example a 3D vector or a IP address:The above functionality could be achieved overloading operators and conversion operators, but the
unionapproach looks neat for me.The
unions can also be templated and can have constructor/destructor, this could be useful for serialization purposes (not for all kind of objects):