Link to home
Start Free TrialLog in
Avatar of dja98
dja98

asked on

static anonymous union member

static member variables have to be declared e.g.
class A{
    static int i;
}

int A::i = 0;

However, what if the variable is an anonymous union e.g.
class B{
    static union{
        int*  pint;
        char* pchar;
    }
}

how do I declare this?

This doesn't work
int*  B::pint;
char* B::pchar;

Nor does this
static union{
    int*  B::pint;
    char* B::pchar;
}
Avatar of AlexFM
AlexFM

Class B, as you wrote it, doesn't contain static member.  But if we add this member, there is a way to declare it outside of class. This code fragment is compiles in VC++ :

class B
{
public:
   static union
   {
       int*  pint;
       char* pchar;
   } u;
};

static union B::__unnamed u;

int main(int argc, char* argv[])
{
    u.pchar = 0;

     return 0;
}


Avatar of dja98

ASKER

But I want to be able to access it as (for example)

int main(blahblah)
{
    B::pchar = "Hello";
    printf("%i\n", B::pint);
}
class B
{
   static union
   {
       int*  pint;
       char* pchar;
   };
}

There is nothing to access here, because union is data type and not object. You can access it's members only if you declare variable of such type.

Suppose you declare structure:

struct sA
{
    int n;
    chas c;
};

The only way to work with sA::n or sA::c is to declare variacle of type sA:

sA a;
a.n = 0;
Avatar of dja98

ASKER

Surely that is only for 'typedef union{blahblah}'.  Otherwise what is the point of an anonymous union of any type?
ASKER CERTIFIED SOLUTION
Avatar of n_fortynine
n_fortynine

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dja98

ASKER

In my code it would have been private - if I can't do it I'll have to rethink - thanks
OK, I got your idea. Trying to play with it I found that VC++ complier ignores static keyword for anonymous union and treats it always as non-static member:

class B
{
public:
   static union
   {
       int*  pint;
       char* pchar;
   };
};


int main(int argc, char* argv[])
{
    B b;
    b.pint = 0;

    B b1;
    b1.pint = new int(2);
    delete[] b1.pint;


    return 0;
}

It is interesting what happens with other C++ compilers.
Microsoft go out of therr way to do so many things standard C++ wouldn't allow that I almost hate to use their compiler. =)
They promise 100% ANSI C++ compatibility in Visual Studio 2003.
> They promise 100% ANSI C++ compatibility in Visual Studio 2003.

I don't think they promise 100% compatibility (e.g. export is still not supported) - I don't think any compiler is 100% compatible yet.  However, it has gone from probably last place in the C++ standards compliance league, to probably first place.