Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: unions with methods?

Tags:

Is there anything wrong with a union having one or more methods? Or anything to watch out for? (I can see constructors/destructors being problematic for schizophrenic reasons)

like image 381
Jason S Avatar asked Oct 29 '10 22:10

Jason S


People also ask

What is union in C with example?

A union is a user-defined type similar to structs in C except for one key difference. Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time.

Can unions have functions?

A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class.

What are C unions used for?

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 are the limitations of union in C?

Here, are cons/drawbacks for using 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.


1 Answers

From the C++03 & C++0x (Draft N3092) standards:

9.5 Unions
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.

Initializing the union using the aggregate initializer syntax (U u = { 42 };) or setting a member afterwards (U u; u.i = 42;) is not "problematic". And neither is initializing it using a constructor (U u( 42 );).
The only "catch" is that you cannot use the aggregate initializer syntax for a union that has a user defined constructor.

like image 104
Eugen Constantin Dinca Avatar answered Sep 20 '22 15:09

Eugen Constantin Dinca