Hey everyone! I'm working with a C++ class that has a parameterized constructor, but the values I need for that constructor aren't available until runtime. Essentially, I'd like to declare a static instance of the class in my program, but I want to pass the value into its constructor during the 'setup' function. My immediate thought was to create a separate member function to set this value, but I wanted to know if there's a better way to handle this situation first. Just so you know, this object is designed to last for the entire run of an embedded application. Any advice would be greatly appreciated!
2 Answers
Can you elaborate a bit more on your issue? Remember, variable values only become available at runtime. Are you asking about a coding challenge or is this more of a conceptual question?
You currently have the object 'a' constructed on the stack, which requires the constructor's parameter to be available at that moment. Instead, you could declare 'a' as a pointer, like so:
```cpp
A* a;
```
Then, you can create it later on the heap inside the setup function with `a = new A(value);`. Keep in mind that you'll need to access it using `a->getVal()` instead of `a.getVal()`. Don't forget to `delete a;` when you’re done.
For better memory management, consider using smart pointers:
```cpp
std::unique_ptr a;
```
And initialize it like this: `a = std::make_unique(value);`. This will help you avoid manual deletion and provides various other benefits!
Just a heads up, though - this approach uses dynamic allocation. If you're looking for a strictly static allocation method while deferring the constructor, check out `std::aligned_storage` and the placement new operator! It’s a more advanced technique.
Thanks for the clarification! This is exactly the kind of solution I needed!
Sure! To clarify, in my example, 'a' is statically allocated, but the value I'd like to pass to the constructor needs to be set in the 'setup()' function. I thought about dynamically allocating 'a' but then wouldn’t be able to use it in the 'update' function unless I deal with pointers. Will the object persist outside of its function's scope?