Consider the class MyClass that has no default constructor.
I want to write a code that looks like the following:
MyClass instance;
void init_system() {
instance = MyClass(parameters, of, the, constructor);
}
The code I wrote above of course fails with the error MyClass has no C'tor that takes no arguments.
Is there any correct way to do it, or I must implement a workaround, e.g. using shared pointers?
Well, either a default object of your class can sensibly exist, or it cannot.
In the latter case, you might be interested in std::optional (boost::optional before C++17) to defer the construction of the object.
You could move the initialization of the object into your init_system() function:
MyClass& init_system()
{
static MyClass instance(parameters, of, the, constructor);
return instance;
}
You may want to look up the singleton pattern, too, and read the extensive discussions about it ;)
And yes, another solution could be to use a unique_ptr<> or shared_ptr<>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With