Report
5 years, 5 months ago.

Defining class instances at runtime

I'm sure this is a dumb question, but how can I call the constructor of an instance from within a function (for example an init function) and have that instance be available throughout the scope of my project?

Here's an example:

#include "mbed.h"

void init(PinName pin) 
{
    DigitalOut myled(pin);
}

int main() 
{    
    init(LED1);
    
    while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}
Comment on this question

1 Answer

5 years, 5 months ago.

With new you can do it (remember that it will then really stay forever, not a problem if you do it like this, but don't do it in a loop without calling delete):

 #include "mbed.h"
 
DigitalOut *myled;

void init(PinName pin) 
{
    myled = new DigitalOut(pin);
}
 
int main() 
{    
    init(LED1);
    
    while(1) {
        *myled = 1;      //Either with '*' to make it into a regular object instead of pointer again
        wait(0.2);
        myled->write(0);  //Or use '->' instead of '.'
        wait(0.2);
    }
}

Didn't test if it compiles, so might have a small error in it.


To post an answer, please log in.