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

0
0
Asked By CuriousCoder47 On

I have a C++ class that I want to allocate statically, but the value I need for its constructor isn't available until runtime. I'm trying to figure out how to properly set this up. Here's the class I've got:

```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();
}
```

The object is meant to last for the entire program since this is for an embedded application. I could create a separate function to set the value, but is there a more proper way to achieve this?

2 Answers

Answered By CodeGuru91 On

You're currently creating 'a' on the stack, so you need the constructor argument at declaration time. A better approach is to declare 'a' as a pointer and allocate it on the heap later. For example:

```cpp
A* a;
a = new A(value);
```

Then, instead of `a.getVal()`, you would use `a->getVal()`. Just remember to delete it with `delete a;` when you're done. A more modern and recommended way is to use smart pointers like this:

```cpp
std::unique_ptr a;
a = std::make_unique
(value);
```

This prevents memory leaks since the smart pointer will automatically manage the memory for you until no longer needed.

NitpickingNora -

Maybe just a nitpick, but this is dynamic allocation, not static allocation. To truly reserve space for an object statically but defer its constructor, you could use `std::aligned_storage` and then construct the object using "placement new".

HelpfulHank -

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

Answered By JustTryingToHelp On

Could you explain the problem a bit more? Variables' values are typically only available at runtime. Are you facing a specific coding issue or is this just for learning purposes?

CuriousCoder47 -

Hopefully this makes sense! In my example, 'a' is statically allocated, but I need the variable for the constructor during the 'setup()' function. I thought about dynamically allocating 'a' in setup, but then I wouldn't access it in update. Would using an object pointer work? Can 'a' outlive the function scope?

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.