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?
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?
The
union
is a C-structure, and does not work well with C++ types (there are a number of caveats actually). However there already exist a C++ equivalent, which effectively work with all C++ classes and user-defined classes and is even safer than the union!Behold Boost.Variant!
You can define a
boost::variant<std::string, Foo, char>
and it'll make sure:And it even comes with the excellent:
boost::static_visitor<Result>
which let's you apply a method on the union regardless of its type and provide compile-time checking to warn you whenever you have forgotten one of the possible types!Also... it's as efficient (fast) as a
union
, and does not involve any dynamic look-up like Boost.Any would.I just added some more things to @maraguida example. I wrote it as a response just to heve more room. It illustrates that not only member functions, but also static member functions and operators can be added.
It can be compiled with: g++ -Wall union_func.cpp -o union_func
The output is:
You can, for example, put a conversion operator to another type of your need, if it make sense to your need.
You can also make a template union :
I don't know if it's valid. Codepad accepts, runs, and gives the expected output from this program
9.5/1
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.