0

GFXcanvas constructor
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

GFXcanvas constructor

by JCalhoun on Sat Jun 05, 2021 9:04 pm

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?

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

Re: GFXcanvas constructor

by adafruit_support_mike on Sun Jun 06, 2021 9:18 pm

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.

adafruit_support_mike
 
Posts: 63052
Joined: Thu Feb 11, 2010 2:51 pm

Re: GFXcanvas constructor

by JCalhoun on Sun Jun 06, 2021 9:43 pm

I understand.

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

Code: Select all | TOGGLE FULL SIZE
GFXcanvas1 offscreenBitmap = NULL;


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

Code: Select all | TOGGLE FULL SIZE
GFXcanvas1 offscreenBitmap = GFXcanvas1.init();


Then of course there is a method that you must call before using the object:

Code: Select all | TOGGLE FULL SIZE
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 | TOGGLE FULL SIZE
GFXcanvas1 *offscreenBitmap = NULL;

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

Re: GFXcanvas constructor

by adafruit_support_mike on Mon Jun 07, 2021 6:11 pm

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.

adafruit_support_mike
 
Posts: 63052
Joined: Thu Feb 11, 2010 2:51 pm

Please be positive and constructive with your questions and comments.