Alok Save
Alok Save

Reputation: 206518

Usage of Union in OOP

Unions can be used as a type just like a class and structure(with some restrictions).It can have member functions. It can be used as an OOP construct.

As I understand unions were just imported in to C++ to maintain backward compatibility with C.
In all these years of programming I have never used an union like I would use an class or a structure as an OOP construct.

Is there any practical usage of Union as an OOP construct(not just as an data type) or it is just some vestigial part of the language that is never useful?


EDIT:
The standard definitely allows union to act as an OOP construct. It allows for member functions in unions. Following code compiles and works and is standard compliant:

union A
{
    int a;
    int k;

    void doSomething(){}

};

int main()
{
    A obj;
    int i = obj.a;
    obj.doSomething();
    return 0;
}

Why does the standard allow member functions in an union if it is not supposed to act as an OOP construct?
Please post answers with specific reasoning and please refrain from posting an answer I don't think so, without a good reasoning of why?

Upvotes: 5

Views: 2502

Answers (6)

TemplateRex
TemplateRex

Reputation: 70526

From the Microsoft help:

C++ union is a limited form of the class type. It can contain access specifiers (public, protected, private), member data, and member functions, including constructors and destructors. It cannot contain virtual functions or static data members. It cannot be used as a base class, nor can it have base classes. Default access of members in a union is public.

It is even possible to template unions (see e.g. Templates - The Complete Guide). In that sense, unions provide almost identical degree of encapsulation.

All those syntactic constraints notwithstanding, unions do fill a small hole in ways to break the C++ type system. Consider these loose correspondences:

class/struct with virtual functions    <--> dynamic_cast
class/struct without virtual functions <--> static_cast
union                                  <--> reinterpret_cast

Polymorphism is all about breaking the type system in a safe and controlled manner. Classes and structs break the type system in time. With virtual functions, we can break the type system at run-time; without virtual functions, we can do it at compile-time (especially with templates). Unions on the other hand, can break the type system in place. Note that polymorphism and encapsulation go hand in hand: whatever is liable to change is hidden from the user (either through vtables, compile-time lookups or data reinterpretation).

Whether this is enough to label unions as being part of the OO style of programming, seems a matter of taste to me.

Upvotes: 1

stefan bachert
stefan bachert

Reputation: 9608

I think no.

unions have nothing to do with object orientation.

C++ never says it intends to support OO only. C++ supports from beginning multiple paradigm (meanwhile: procedural, functional, generative, object oriented)

The C++ 11 supports "unrestricted unions" but I do no see any usage from the OO perspective

Depending on authors object orientation requires the following issues:

  • identity
  • inheritance / generalism
  • polymorphy
  • encapsulation

In case of unions the first issue is valid. An union could be identified (by its address for example)

There is NO concept of inheritance available for unions.

One could argue data is polymorph in a union, but this interpretation is far from what oo considers to be polymorph. A union could not have virtual function which would be nearly useless without inheritance. And it would break the memory layout.

There is encapsulation in an union. However, due to limitations I do not expect useful applications for this case. If any I would appreciate a link

With this set of features I would consider "abstract data type" (ADA) as to be the right term.

Upvotes: 1

No, a union is not an OO construct.

The single most important feature of OO is polymorphism, but unions cannot participate in a inheritance relationship (cannot be a base of a different type, cannot have bases itself) or have virtual functions. The only purpose of an union is to provide a data type, not an object.

Upvotes: 5

Robert Mason
Robert Mason

Reputation: 4039

It's not good practice, but suppose you could make a strong guarantee that only one field would be active:

class multi_type {
private:
    bool unit_is_float;
    union {
        float float_member;
        int int_member;
    };
public:
    multi_type(bool is_float) : unit_is_float(is_float) {}
    bool isFloat() { return unit_is_float; }
    bool isInt() { return !unit_is_float; }
    float& getFloat() {
        if (!isFloat()) throw std::logic_error("not a float");
        return float_member;
    }
    int& getInt() {
        if (!isInt()) throw std::logic_error("not an int");
        return int_member;
    }
};

Formatted to be concise, not pretty.

A valid application might be in some sort of parsing library where the language to be parsed can have different types of tokens which can only be determined at run-time. It's an alternative to using void*s.

Upvotes: 1

Christopher Oezbek
Christopher Oezbek

Reputation: 26353

As a low level construct a union is then useful if your data has different interpretations and types based on context. In this sense, it helps you keep your objects smaller than if you keep different fields which cannot exist concurrently.

Is that a valid concern for OOP? Kind of, I guess...

--

One hack people do with them is access different bytes with different names (typical examples is to have a union of 4 bytes r,g,b,a and one 32 bit integer color), but this is potentially dangerous https://stackoverflow.com/a/1582389/278842.

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67195

My personal view is "no".

Historically, C has allowed developers low-level access to the host system, accessing memory in very flexible ways. By providing a construct to treat the same area of memory as different data types, this flexibility was made even easier.

But it's hard to see how this can be classified as any type of object-oriented construct.

Upvotes: 1

Related Questions