How to Create a Static Object with Runtime Parameters in C++?

0
2
Asked By CuriousCoder92 On

Hey everyone! I'm facing an issue with a C++ class that I want to statically allocate, but its constructor requires parameters that won't be available until runtime. I'm looking to pass these values in the 'setup' function, but I'm not sure how to do it properly. I know I could create a separate member function to handle the values, but I want to explore any better solutions first. Just to give you some context, this object is supposed to last for the entire duration of the program, as it's meant for an embedded application. Thanks in advance for any help! Here's a quick look at my class:

```cpp
class A {
public:
// Parameterized Constructor
A(int x) {
val = x;
}

int getVal() { return val; }
private:
int val;
};

A a(0);

void setup() {
int value_that_i_want_to_go_in_constructor;
}

void update() {
int b = a.getVal();
}
```

2 Answers

Answered By LearningLarissa On

Can you clarify what your issue is? Just remember that values are generally only available at runtime, and an object can last as long as necessary. Is this a coding question or are you learning concepts?

CuriousCoder92 -

I hope this clarifies it! In my code, 'a' is already statically allocated, but I want to use a variable from the 'setup()' function for the constructor. Would dynamically allocating 'a' in 'setup' allow me to access that value without losing it in 'update'? I suppose I could assign 'a' to an object pointer — would it still exist after 'setup'? I'm still figuring this out!

Answered By TechieTurtle On

You're currently creating the object 'a' on the stack, which means you need the parameter for the constructor when you declare it. Instead, consider using a pointer like this:

```cpp
A* a;
```
Then, create it later on the heap with `a = new A(value);`. You would access it using `a->getVal()` instead of `a.getVal()`. Don't forget to call delete when you're finished with it, or better yet, use smart pointers for safer memory management:

```cpp
std::unique_ptr a = std::make_unique(value);
```
This way, you won't have to worry about deleting it later!

DevNerd -

Just a quick note: this method is dynamic allocation. If you want to actually *statically* reserve space for the object but defer construction, you might want to consider using `std::aligned_storage` with the placement new operator.

User99 -

Thanks! This is exactly what I needed.

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.