I’m new to OF and trying to simply create an array of rectangles using a class. Does anyone have example code I could look off to get an idea of how to do this?


you mean for reading about arrays?


I have a class Button and I just wasn’t sure where to declare the array, for example would buttons[]= new Button;
go in the file?

you can do for example: #define nButtons = 3 in testApp.h and Button buttons[nButtons];

I suggest you to use containers instead of arrays:

They are more efficient and cleaner to work with.

Regarding your question, you can:
1-Create your class…

2-In the TestApp.h import the class
#include “MyClass.h”

3-Declare the variable with the amount of objects you want to create:
static const unsigned int AMOUNT = 10;

4-Declare the container you want to use. In most cases you will go for a vector.
std::vector mObjects;

5-Create a typedef with the iterator for the container. You will use this to access the methods on your class.
typedef vector::iterator mIter;

6-On the implementation (.mm or .cpp file) iterate with a for loop to instantiate your objects:
for(unsigned int i=0;i<AMOUNT;i++){

7-Depending how your class is implemented, you can access its methods by using the container’s iterator:

for(mIter i=mObjects.begin(); i!=mObjects.end();++i){

…do the same with draw or the methods you declared on your class

8-If you are using a lot of elements I would suggest using pointers and smart pointers to have a good memory house keeping.

hope it helps!

Thanks for the example. Is it possible to do this with images?
vector images;
then something like:

I’m also assuming I don’t need a separate class for image?

Vectors can be filled with any type (int, float, ObjectX or ObjectY). The important thing is to instantiate them accordingly: vectorX.push_back(ObjectX(x,y,z));

Probably a very stupid question but how do you add images to the vector?
Is it possible to do images[0].loadImage(“1.png”); ?

hm, you can also use a vector with pointers to images

vector <ofImage*> Pics;  

create & load with

Pics.push_back(new ofImage());  
Pics.push_back(new ofImage());  
Pics.push_back(new ofImage());  

draw them

for(int i=0;i<Pics.size();i++) {  
Pics[i]->draw(0, 0);  

this has several advantages & disadvantages…(pointers, passing vale to other classes, boa…)

greetings ascorbin

1 Like

Thank you. It’s compiling without errors but for some reason my images are white squares.

use ofEnableAlphaBlending();