Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 10 months ago.
Why use new to declare classes and variables?
In some examples of code I've seen people declare object variables as pointers to classes using new and I've also seen GPIOs declared using new in classes. Why is this done when most classes are used for the life of the program and only destroyed at a reset and a pointer to a class or library object (digitalin and digitalout are 2 I've seen) unless declared as global are only available in portions of your program? Cheers Mike
1 Answer
9 years, 10 months ago.
There can be multiple reasons. Sometimes it just has no advantages to defining it the 'regular' way. But one reason to use 'new' is because it is an optional pin. These days it is possible again to make an optional pin as 'NC' again, but that wasn't possible for a while, making 'new' the only working solution. But even if it is possible, there is something to say for not constructing pins which are not connected.
And sometimes it also is the case that they have variable size or lifetime, and new is the best solution for a variable.