Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Assign value to global class variable

Tags:

c++

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?

like image 441
SomethingSomething Avatar asked Feb 14 '26 09:02

SomethingSomething


2 Answers

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.

like image 109
Quentin Avatar answered Feb 16 '26 23:02

Quentin


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<>.

like image 36
Rene Avatar answered Feb 16 '26 23:02

Rene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!