How can I create a static object with a parameterized constructor using runtime values in C++?

0
4
Asked By CuriousCoder42 On

Hey everyone! I'm working with a C++ class that has a parameterized constructor, but the value I need for that constructor won't be available until runtime. I want to statically allocate this object, but I'm unsure how to properly pass the value to the constructor in the 'setup' function. I considered making a separate member function to set the value, but I'd like to know if there's a better or more 'proper' way to handle it. Just to clarify, the object is meant to last for the duration of my embedded application. Thanks in advance for any insights!

2 Answers

Answered By DebuggerDude On

Can you clarify the issue a bit more? Variables are only known at runtime, and objects can last as long as you need them. Is your concern about the coding side or more about concepts?

CuriousCoder42 -

Hi! So, in my code, 'a' is statically allocated, but the value I want to use in the constructor is only available in the 'setup()' function. I thought about dynamically allocating 'a' in 'setup()', but then accessing it in the 'update' function becomes tricky. Maybe I could use a pointer for 'a' and create it inside 'setup'? Will the object survive after the function scope?

Answered By TechieTom123 On

You're currently declaring 'a' on the stack, so you need that parameter at the time it's constructed. Instead, consider using a pointer. Declare it like this: `A* a;` and then construct it on the heap later using `a = new A(value);`. To access the value, you’d use 'a->getVal()'. Don't forget to call 'delete a;' when you're done. But I'd recommend using smart pointers for safety: `std::unique_ptr a;` and then `a = std::make_unique(value);`. This way, you don’t have to manually delete it later, which is super helpful!

CodeNerd89 -

Just a heads up, this solution involves dynamic allocation, not static allocation. For true static reservation while deferring construction, you could use `std::aligned_storage` and then construct the object with 'placement new' after the space is allocated.

HelpfulHank -

Thank you! This is exactly what I'm looking for.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.