Willie Willie - 1 year ago 64
C++ Question

Construct class with 'const' parameters during runtime

This is probably a simple question, but I can't find a good way to solve it. I am using an API which has a class, whose constructor need const double as its parameter, such as:

MyClass(const double value);

The problem is that I want to construct a series of instances but the value passed can only be known during runtime.

More clearly, here is what I have done:

.h file

std::vector<MyClass> my_class_vec;
std::vector<double> my_value_vec

During runtime, I can get the values to make my_value_vec assigned. I want to use these values to construct my_class_vec:

.cpp file

for(int i = 0; i < my_value_vec.size(); i++)

I know this is wrong, because I can't pass double as a const double parameter. And I also have some incorrect usages on instance construction, but I can't find a good way to do what I want. Does anyone have any ideas? I really appreciate for your opinions.

Answer Source

This is wrong, but for a completely different reason. For starters, but you can certainly pass a double as a const double parameter.

void foo(const double b)

double c;

void bar()

This will compile with no issues, whatsoever. The only thing that const specifies, in this case, is that the function, foo(), cannot modify its parameter. That's it. It bears no relevance, whatsoever, on whether the passed value is constant or mutable. The caller is free to pass either double, or a const double as a parameter. This parameter is passed by value. This means that a copy of the parameter is made, in every case, for the called function. The copy can come from a double, or a const double, it makes no difference.

Your problem is completely different. The attempt to construct the vector is fundamentally wrong.1all wrong.

std::vector<MyClass> my_class_vec;
std::vector<double> my_value_vec;

my_class_vec is a vector.


This will not compile for the simple reason that std::vector does not implement operator(), which is being invoked here. my_class_vec(something) does not add anything to a vector. There's no such thing. This doesn't construct anything. This attempts to invoke operator(), passing a double as a parameter, on the object. Since a std::vector does not implement the () operator, this fails to compile.

The correct way to initialize your sample vector, using modern C++:

for (const auto &value:my_value_vec)

This assumes that my_class_vec is empty. emplace_back() constructs a new value at the back end of the vector, passing the double value to the constructor. Note that this will work with or without the const qualifier in the range iteration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download