Go Down

Topic: My class does not name a type (Read 1 time) previous topic - next topic

ardudillo

Hello guys, I am having surprising amounts of trouble with something that ought to be trivial. The code below compiles fine:

Quote

class Foo {
  public:
    int x;
    
  Foo(float f) {
    x=(int)f;
  }
  
  int getX() {
    return x;
  }
  
};


void setup() {
  
  Foo f = Foo(3.1415927);
  
}

void loop() {
}



My class Foo is perfectly useable in setup and all is perfect with the universe. That is, until I try using it as a return value or an argument to a function e.g. adding this after loop():


Quote

Foo zonk(float f) {
  return Foo(f);
}



Gets me a:
error: 'Foo' does not name a type


while this:

Quote

int zonk(Foo f) {
  return f.getX();
}



tells me that:
error: 'Foo' was not declared in this scope

Why is the great big chunk of code defining the class at the start of the sketch not good enough when trying to use the class in this context?

PaulS

Putting the class definition in a separate file, Foo.h, and #including Foo.h in the sketch lets the int zonk function compile.

ardudillo

Ah, thank you. I was hoping I wouldn't have to write a library if all I want to do is use a small class but anyway, I did and it worked.

dcb

you can also put the class/function prototypes at the beginning of the script.  Which may be more appropriate than splitting things into separate files for this sized application, easier to share it and for folks to run it then too.

Go Up