Hi,
I plan to have different classes with similar methods, say "loop()".
I then want to make instances of the classes and store them in an array so I can call loop() of all the objects.
something like:
Tiger *objArray = [10];
objArray[0] = new Tiger();
//the problem is this
objectArray[1] = new Dog();
objectArray[2] = new Penguin();
void loop() {
for(int i =0; i < 3; i++) {
objectArray->loop();
}
}
So as you can see the array is type Tiger. How can I include Dog and Penguin?
Derive them all from the same class.
Example:
class animal
{
public:
virtual void loop () = 0; // pure function
};
class Tiger : public animal
{
public:
void loop () { Serial.println ("Tiger."); }
};
class Dog : public animal
{
public:
void loop () { Serial.println ("Dog."); }
};
class Penguin : public animal
{
public:
void loop () { Serial.println ("Penguin."); }
};
animal * objArray [3];
void setup ()
{
Serial.begin (115200);
objArray [0] = new Tiger;
objArray [1] = new Dog;
objArray [2] = new Penguin;
} // end of setup
void loop ()
{
for (int i = 0; i < 3; i++)
objArray [i]->loop ();
delay (1000);
} // end of loop
Output:
Tiger.
Dog.
Penguin.
Tiger.
Dog.
Penguin.
Tiger.
Dog.
Penguin.
Thanks!
I had a feeling that was the answer like in any other language and was looking around how to sub-class in C/Arduino.
Oh by the way, is there a destructor function that is called when I delete?
like
delete objArray[0];
do I need a destructor in the class
void desctructor() {
//not sure if I need to do this
delete super;
}
I come from Objective C and we have a dealloc function in every class that cleans up after itself.
This is C++ by the way, not some "Arduino language".
If you plan to use a destructor to clean up then the destructors must be virtual, including the base class.
Modified example:
class animal
{
public:
virtual void loop () = 0;
virtual ~animal () { Serial.println ("animal destructor."); }
};
class Tiger : public animal
{
public:
void loop () { Serial.println ("Tiger."); }
virtual ~Tiger () { Serial.println ("Tiger destructor."); }
};
class Dog : public animal
{
public:
void loop () { Serial.println ("Dog."); }
virtual ~Dog () { Serial.println ("Dog destructor."); }
};
class Penguin : public animal
{
public:
void loop () { Serial.println ("Penguin."); }
virtual ~Penguin () { Serial.println ("Penguin destructor."); }
};
animal * objArray [3];
void setup ()
{
Serial.begin (115200);
Serial.println ();
objArray [0] = new Tiger;
objArray [1] = new Dog;
objArray [2] = new Penguin;
for (int i = 0; i < 3; i++)
objArray [i]->loop ();
Serial.println ("Deleting objects ...");
for (int i = 0; i < 3; i++)
delete objArray [i];
} // end of setup
void loop () { }
Output:
Tiger.
Dog.
Penguin.
Deleting objects ...
Tiger destructor.
animal destructor.
Dog destructor.
animal destructor.
Penguin destructor.
animal destructor.
Be warned that there is a problem with free (and hence delete) in versions of the IDE up to 1.0.3.
You may need to install the fix described here: Fixing String Crashes