GFXcanvas constructor

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
JCalhoun
 
Posts: 2
Joined: Sat Jun 05, 2021 8:58 pm

GFXcanvas constructor

Post by JCalhoun »

More of a general C++ question.

For microcontrollers like the Arduino, we often declare globals, for example a bitmap GFXcanvas1.

I understand that in C++ when I declare an object, I must "construct" it. For GFXcanvas1() that is width & height  — example: GFXcanvas1 (128, 32);

My problem is that I don't know the width and height at compile time, it is something too that may change dynamically at runtime.

I'm familiar with other languages, but this particular aspect of C++ is new and frustrating to me.

Is there a way to declare perhaps a global pointer to a (NULL) GFXcanvas1 object and then construct/destruct at runtime?

User avatar
adafruit_support_mike
 
Posts: 67485
Joined: Thu Feb 11, 2010 2:51 pm

Re: GFXcanvas constructor

Post by adafruit_support_mike »

The existing GFXcanvas1 class requires width and height values when it's created, because those are used to allocate memory for the bitmap raster. They're also used to calculate bit offsets when you want to read or write bits in the raster.

You could modify the class so the dimensions and memory buffer can be changed after the object is created. I don't see any value in that over creating a new GFXcanvas1 object every time you need new dimensions though. The existing contents of the buffer wouldn't be any good after the width and heigh values change.

User avatar
JCalhoun
 
Posts: 2
Joined: Sat Jun 05, 2021 8:58 pm

Re: GFXcanvas constructor

Post by JCalhoun »

I understand.

This is not allowed in C++ as a global declaration (I wish it was):

Code: Select all

GFXcanvas1 offscreenBitmap = NULL;
I was hoping the constructor did nothing, so this would be legit, but not specify width/height:

Code: Select all

GFXcanvas1 offscreenBitmap = GFXcanvas1.init();
Then of course there is a method that you must call before using the object:

Code: Select all

offscreenBitmap.begin (32, 128);
It would of course free any existing buffer, malloc a new buffer. The added complexity of course is that everywhere in the class code it would have to do a sanity check to make sure there is a buffer — that begin() was called.

Perhaps though I can work around this by declaring a (NULL) pointer to a C++ object:

Code: Select all

GFXcanvas1 *offscreenBitmap = NULL;

User avatar
adafruit_support_mike
 
Posts: 67485
Joined: Thu Feb 11, 2010 2:51 pm

Re: GFXcanvas constructor

Post by adafruit_support_mike »

Yeah, that adds more complexity to the code. You'd have to make sure the object reference was non-null before using it, check to see if there was a buffer, and so on.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”