I can't think of a very common case. However, in some recursive data
structures (e.g., trees), you might want each conceptual node to be either a
"real" node or a "nill" node. There are many different ways of implementing
such a data structure. Suppose you're *really* concerned about indirection
(i.e., you wish to avoid it). Then you might create a vector whose each
element an object of
struct node
{
bool m_real_node;
union m_true_node
{
real_node m_real_node;
nil_node m_nil_node;
}
};
So that's a case where you might use a union. As far as I understand, the
above (quite ugly) example should be used in very extreme circumstances (if
you're convinced this will actually improve performance), and you should
encapsulate the hell out of it into a container employing such nodes
internally.
By the way, I vaguely recall the above code working ~3 times as fast as a
version I wrote without unions (based on pointers, and using NULL to signify
a "nil" node) (of course, since I wrote them both, who knows what I might
have fudged, also, it's been years, and I can't recall the exact settings).
"Michael" <sl***********@hotmail.com> wrote in message
news:ct**********@hercules.btinternet.com...
Hi guys I've been programming C++ for quite some time, but I have never
used unions. I am trying to find a good exmaple of when they might be used. can
anyone provide one??
Regards
Michael.