Unions and Classes in C++

C++ also supports unions as in C. They are functionally similar to that of a class but has the following limitations:

  • All members are public by default
  • Cannot be a base class to inherit other classes
  • Cannot have virtual functions
  • Cannot include static variable
  • An object using a constructor and destructor cannot be a member of a union

One of the advantages of using Unions is that all data elements share the same memory. So they are commonly used when we require that the variables share a common memory. An example usage of union is shown below –

#include <iostreams.h>

main(){
       Union{
             int i;
             const char* name;
             };
        i = 21;
        name = "Tony";
        cout << "Name:" << name << " Age:" << i << "year";
}

The above is an example of Anonymous Union without a type name. This could not include member functions, private or protected regions as with usual union and if declared globally, it must be static.

Add a Comment

Your email address will not be published. Required fields are marked *