Anonymous structures/Unions?


We have anonymous unions...anonymous structures also possible?

When do we require these nameless structures/unions? I am clueless

I am new to c++...Please help


Thanks in advance
Prasad
There is a distinction between the terms unnamed and anonymous. Only unions can be anonymous, any class type can be unnamed.

Anonymous union is what you use when you want to "unionize" some, but not all members of some class/struct:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Variant {
    int tag;
    union { // anonymous union
        int i;
        double d;
    };
}; // this class appears to have three members: tag, i, d
int main()
{
    Variant v;
    v.tag = 2;
    v.d = 3.14;
}


or when you want to unionize a few regular variables:

1
2
3
4
5
6
7
8
int main()
{
    union { // anonymous union
        int n;
        double d;
    }; // n and d can be used like local variables
    d = 3.14;
}


Unnamed unions/structs/classes are just helper types introduced just to declare one object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
union { // unnamed union
    int n;
    double d;
} u;

struct { // unnamed struct
    int n;
    double d;
} s, *p;

int main()
{
    u.d = 3.14;
    s.n = 1;
    p = &s;
}

Topic archived. No new replies allowed.