C++ coding, instances & pointers in OF


I have a question about the C++ “coding style” of openframeworks…

I’ve seen a lot of examples and codes from reps that use instances by reference without pointers, I mean, to create an ofImage, the code on the examples is something like:

ofImage img;

working with an instance of an object, I’m expecting a pointer created by the new operator in this way:

ofImage *img = new ofImage();

The only “new” operator I’ve seen is on the main method:

ofRunApp(new testApp());

Are there any reasons why in openframeworks the way to use objects is not by using pointers and the -> operator?
Just to know if it’s a coding style or a specific requirement.


In OF we have a tendency to avoid using the new operator for a few reasons:

  1. Dynamic memory allocation (new, malloc) is a common cause of memory
    leaks for new c++ programmers
  2. Pointers are a common cause of headaches for non c++ programmers
  3. Allocating on the stack is faster then the heap

Obviously, once you start looking at memory (getPixels(), etc) actually having pointers makes sense and are very useful, but for most casual uses, stack allocation seems to work fairly well. It’s important to point out that OF started as a tool for teaching, so some of the design decisions were made regarding beginners / new to c++ users.

There’s some pattern info in this tutorial @arturo made – might help you understand some of the design of OF:

hope that helps!

Thanks Zach,

as I had a lot of headaches in the past, now I prefer to work with C++ with pointers if there is nothing wrong…

there’s no problem working with pointers / dynamic allocation of OF objects and I do that all the time, it’s just useful to know about how we handle objects that use opengl resources, ie, shallow copies, etc. (see arturo’s tutorial re: patterns for some info).