Best struct questions in July 2011

Naming Conflict in C++: How to access a struct member called "class"

15 votes

I came across a naming problem while working with the xlib library:

I'm using a struct which has a member called "class". I assume this library is mostly used in plain C programs. So there's no problem.

But I'm programming in C++ and here the name "class" is a keyword and cannot be used to denote variables. So, if I'm accessing the struct via

myvariable = mystruct->class;

I'm getting the error:

expected unqualified-id before ‘class’

Given that I cannot change the struct itself, how can I access this struct member despite the naming conflict?

You say that you're using XLib. I can only find two places in my Xlib.h where class is used as a structure member: Visual and XWindowAttributes. In both cases, the offending member is wrapped like this:

#if defined(__cplusplus) || defined(c_plusplus)
    int c_class;
#else
    int class;
#endif

Similar hackery appears in XColormapEvent to take care of the new member.

So you should be fine unless your C++ compiler isn't defining any of the necessary macros; but that would also break the usual extern "C" { ... } wrappers as well so the problem is most likely elsewhere. If you're using a struct that isn't part of the standard XLib then you should apply the above hack by hand and have a stern discussion with the library's author (and if that's you then angrily talk to yourself for a bit and we'll pretend not to listen).

If you are having trouble with the XLib structs, then try using the C++ version of the member names:

myvariable = mystruct->c_class;
mynew      = ev->c_new;