On Oct 3, 2:38 pm, Bit Byter <takashi_...@hotmail.comwrote:
I just realized that I cant use a union in an initialization
list (or at least not the way I tried to use it).
This is what I did:
class ValueObject
{
public:
ValueObject();
ValueObject(const ValueObject&);
ValueObject& operatr= (const ValueObject&);
private:
union Item { int i, double d, char s[8]} m_item ;
enum { integer, Double, String } m_type ;
};
//impl:
ValueObject():m_type(Integer), m_item.i(0) //<- compiler complains
{}
That's because the syntax doesn't allow it. I suppose it could,
in the case where the element was an agglomerate with a trivial
constructor, but the language standard doesn't provide for it.
ValueObject():m_type(Integer)//<- compiler ok with this - why?
{m_item.i(0);}
The line in your constructor body is legal? I should only be
legal if m_item.i were a function. In the constructor body, you
have to use assignment.
There are two possible solutions. The simplest is just use
assignment. All union members are required to have trivial
constructors, so there is no difference between initialization
and assignment. Otherwise, you can provide the union with a
constructor, e.g.:
union Item
{
int i ;
double d ;
char s[ 8 ] ;
Item( int i ) : i( i ) {}
Item( double d ) : d( d ) {}
// ...
} ;
Or unless there are literally millions of these objects, just
use a struct. (That's what I did in a similar case.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34