Can a union in C++ have a member function? How do union with data members and member functions exist if an object is created?
If I suppose yes, then are they feasible any where. If yes then where?
C unions allow data members which are mutually exclusive to share the same memory. This is quite important when memory is valuable, such as in embedded systems. Unions are mostly used in embedded programming where direct access to the memory is needed.
Disadvantages of union. You can use only one union member at a time. All the union variables cannot be initialized or used with varying values at a time. Union assigns one common storage space for all its members. Only one member can be accessed at a particular period of time.
Both structure and union are user-defined data types in C programming that hold multiple members of different data types. Structures are used when we need to store distinct values for all the members in a unique memory location, while unions help manage memory efficiently.
A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.
9.5/1
A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class. An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects
What do you mean by How do union with data members and member functions exist if an object is created? Member functions (non-virtual) take no space in an instance of any class/union.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With