Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union in c++ are they feasible

Tags:

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?

like image 669
Vijay Avatar asked Mar 11 '11 15:03

Vijay


People also ask

Are unions useful in C?

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.

What is the disadvantage of union in C?

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.

Why union is better than structure in C?

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.

Can we use union in structure in C?

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.


1 Answers

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.

like image 188
Erik Avatar answered Sep 19 '22 16:09

Erik