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?
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.
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.
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.
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