Skip to main content
edited tags
Link
VE7JRO
  • 2.5k
  • 19
  • 28
  • 31
Source Link
jbyrnes
  • 103
  • 1
  • 2

How to loop over objects or pass object to function?

I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea.

I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array.

However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try.

I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination.

I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with & or * to explain what I want:

SomeClass classA();
SomeClass classB();

// error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested
SomeClass things[2] = {classA, classB};

int init(class SomeClass thing) {
    std::cout << "Setting up thing ";
    thing.setFoo(100);
}

int main() {

    for (int i=0; i < 2; i++) {
        things[i].setFoo(100);
    }

    // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’
    init(classA);

    return 0;
}

And just for completeness my class files which are simplified versions of the AccelStepper class:

SomeClass.h:

#include <stdlib.h>

class SomeClass
{
public:
    SomeClass();

    void    setFoo(float foo);
};

SomeClass.cpp:

#include <stdlib.h>
#include <string>
#include <iostream>
#include "SomeClass.h"

SomeClass::SomeClass()
{
}

void SomeClass::setFoo(float foo)
{
    std::cout << "foo ";
}

I hope someone doesn't mind explaining what is probably really simple and obvious! :)