1

I haven't needed classes before in programming for Arduino, but I now have a good use case. I'm not sure I grasp how this will affect code space, though.

Currently I have a struct that holds the properties of an object, and common code that iterates over an array of 12 of that struct. It's fairly compact.

It would be cleaner to wrap the operations on the struct in a class and act on an array of 12 of that class. Essentially the current struct would become private data of the class.

Will all the code in the class be repeated in each instance, or is the compiler clever enough to avoid such repetition?

Any clarifications welcome. C++ is not my main language.

1

No, it is not repeated. Unless you are using templates, each method of each class is stored only once in the compiled program. Or even not stored at all if the optimizer notices it is not used.

Just to demystify the classes a bit, you can consider them as a kind of “syntactic sugar” over an “object oriented” programming pattern. The following C++ code:

class MyClass {
public:
    int aMember;
    long anotherMember;
    int aMethod(short);
};

int MyClass::aMethod(short theParameter)
{
    return aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    objects[1].aMethod(42);
}

is interpreted by the compiler as being roughly equivalent to this C code:

typedef struct {
    int aMember;
    long anotherMember;
} MyClass;

int MyClass_aMethod(MyClass *this, short theParameter)
{
    return this->aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    MyClass_aMethod(&objects[1], 42);
}

Can you spot the differences and the similarities?

  • I get the idea but I'm not sure how to interpret return aMember + theParameter; In any case, the main question is answered, so thanks. – Jim Mack May 8 '19 at 20:25
  • @JimMack: Within a method, the class is used as a sort of namespace. So the compiler knows that aMember actually means this->aMember. – Edgar Bonet May 8 '19 at 20:29
1

No, the code is not repeated for each instance. Instance methods are like functions. There is only one copy of the code.

There's a dispatch table that maps method calls to their implementations. (Actually, that's standard C++. I don't know for sure how it's implemented in the Arduino C++ compiler)

  • Dispatch table is only used for virtual methods. As long as we are talking about non-virtual methods, everything works exactly as @Edgar Bonet described. No need for any tables. Arduino IDE C++ compiler is C++11 compiler with GNU extensions. – AnT May 8 '19 at 21:16
  • Important distinction about virtual methods. Thanks for pointing it out. – Duncan C May 8 '19 at 21:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.