5 years, 6 months ago.

Try to put a class instance into a union - works with GCC but not with mbed


I kindly ask for help with a syntax error. I wrote a union declaration:

union declaration containing a class instance

typedef union uTelemetryDataValue {
    float       f;
    q1516_t     q;
    int32_t     i;
    uint32_t    u;
    uTelemetryDataValue() { q= q1516_t(0); }
} tdValue_t;

...and the type q1516_t is a class (you'll guess it) for a fixed point data format:

class declaration of the instance in question

class q1516 {
    int32_t v;
    int32_t getv() { return (v); }
    q1516() { v=0; }
    q1516(const int opnd) {
        if (opnd>=32768 || opnd<-32768) throw_(q_rangeviolation);
        v= INT2Q1516(opnd);
    int16_t toInt() { return (int16_t)(v>0? (v)>>16 : ((v)>>16)+1); }
    int16_t rndInt();
    char* toString();
    char* toString(char *dst, const int before, const int after);
    q1516 operator=(const q1516& q) { v=q.v; return (*this);}
    q1516 operator=(const int i);
    friend q1516 operator+(const q1516& left, const q1516& right);
    friend q1516 operator+(const q1516& left, const int right);
    friend q1516 operator+(const int left, const q1516& right);
typedef q1516 q1516_t;

...and quite a lot of other operator methods and friend operator routines.

I already have tested q1516 on a PC using GCC and in mbed on a NUCLEO and it worked. I already have compiled and tested the union on a PC using GCC and it worked. Now, within mbed, I get a syntax error message

Invalid union member - class "q1516" has disallowed member function followed by the source line "q1516_t q;".

The Help button doesn't yield a help page, just a "not found" message. I never have heard from such a problem and do not khow what to do.

Thank you in advance, sincerely

Helmut Stettmaier

Question relating to:

1 Answer

5 years, 6 months ago.

A google resulted:


A union can have member functions (including constructors and destructors), but not virtual functions. A union shall not have base classes. A union shall not be used as a base class. An object of a class with a non-trivial constructor, a non-trivial copy-constructor, a non-trivial destructor, or a non-trivial copy assignment operator cannot be a member of a union, nor can an array of such objects. If a union contains a static data member, or a member of a reference type, the program is ill-formed.

For what is non-trivial, see this explanation: http://stackoverflow.com/questions/3899223/what-is-a-non-trivial-constructor-in-c

The TL;DR is: Everything you write yourself is non-trivial. So if I am not mistaken, according to the C++ standard your construction is not allowed. Not every compiler follows the standard exactly, so GCC does allow it, and Keil (the mbed compiler) apparantly follows it stricter.

Accepted Answer