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.