JCSB
JCSB

Reputation: 385

Error implementing a struct constructor in C

I get this error from trying to implement a constructor with a struct in C. I do not understand as I follow what I read online

#170 a function type is not allowed here    

Here is the struct definition.

typedef struct ConnectionTestResults_t {

        ConnectionError_t detectedErrors;
        bool isTempShorted;
        bool isRespShorted;
        int8_t conn1ShortedPins[2];
        int8_t conn2ShortedPins[2];
        int8_t spo21ShortedPins[2];
        int8_t spo22ShortedPins[2];
        int8_t usbShortedPins[2];
        int8_t conn1OpenPins[2];
        int8_t conn2OpenPins[2];
        int8_t spo21OpenPins[2];
        int8_t spo22OpenPins[2];
        int8_t usbOpenPins[2];
        ConnectionTestResults_t() {
            conn1ShortedPins = {-1,-1};
        }

} ConnectionTestResults_t;

Thanks!

Upvotes: 0

Views: 337

Answers (1)

chrisb
chrisb

Reputation: 393

Constructors are a c++ (etc) thing, you would normally associated them with Object Oriented programming, which C is not.

If you wanted to, you could implement an initialisation function, something along the lines of;

function void someFunction(ConnectionTestResults_t * instance) {
   ...
}

function void initConnectionTestResult(ConnectionTestResults_t * ctr) {
  ctr->myFunc = &someFunction;
  ctr->initialisableValue = INITIAL_VALUE;
}

(apologies for syntax, been a while since I've done C programming)

If you wanted to implement something like OO methods, the closest you could reasonably come would be;

ConnectionTestResults_t thing;
initConnectionTestResult(&thing);
thing.myFunc(&thing);

Including a type field, and switching on that is another way of achieving it.

if (thing->isAFoo) {
  fooIt(&thing);
} else {
  barIt(&thing);
}

but consider if that's the right way of achieving your objective first.

Upvotes: 1

Related Questions