Object Instantiation

Hi. I'm new to the Arduino platform and C/C++ language (have some years of experience with other languages).

My program requires me to create an object and store it's pointer [b]Foo* foo = new Foo();[/b] in the setup phase, so that it can be accessed in loop method. I don't know how to do it or if it is possible with arduino.

I currently get [code]undefined reference to `operator new(unsigned int)'[/code] for each instance of the new command.

If it makes a difference, Foo is kind of like:

class Bar {
  private :
    void* pointer1;
    void* pointer2;
  public :
    Bar() : pointer1(null), pointer2(null) {}

    void do() {
      //various
    }

    //accessors + mutators
}

class Foo {
  private :
    Bar bar;
    int counter;
  public
    Foo() : counter(0) {}

    void doBar() { bar.do(); }

    //accessors + mutators
}

There is no "new" on the Arduino.

Foo foo; is the best you can do.

The problem is I don't want the compiler to destroy foo once the setup method ends. I need to create a varying number of instances that is determined by a Serial.read call.

So, give them global or static scope.

Found a solution to my problem: #define NEW(x,y) *(x=(y*)malloc(sizeof(y)))=y Kind of recreates the standard new operator. First is uses malloc to allocate enough space to fit the class, casts it to the correct pointer type and assigns it to the variable. The value (object) then has it's constructor run to initialise the member fields

Usage: On a separate line NEW(destinationVariable,Class)(constructorParamList);

Sample

#define NEW(x,y) *(x=(y*)malloc(sizeof(y)))=y

class Bar {
  private :
    int counter;
  public :
    Bar() : counter(10) {}
    
    int get() {return counter++>>1;}
};

class Foo {
  private :
    int counter;
    Bar bar;
  public :
    Foo(int x) {counter=x;}
    int get() {return bar.get()+counter++;}
};

Foo* foo;

void setup() {
  Serial.begin(9600);
  NEW(foo,Foo)(10);
  Serial.print("foo's address: ");
  Serial.println((int)foo);
}

void loop() {
  Serial.println((foo->get()));
  delay(500);
}

My output:

foo's address: 456
15
16
18
19
21
22
24
25
27
28
30
31
...

Notes: The define statements leaves room at the end for any constructor parameters, so the () are required. The return type of NEW(x,y)() is of type y, not *y. The y() constructor also initialises direct field objects (in the example bar). To assign to more than one variable do something like NEW(a=b=c,Foo)(10).