I'm learning C++.
I want to declare a variable without creating an instance of it.
MyClass variable;
// More code
int main(int argc, char **argv)
{
// More code
variable = MyClass(0);
// More code
}
If I do that, and MyClass
only has a constructor declared MyClass::MyClass(int value)
it fails.
I need to make it global because I'm going to use it on a CallBack function and I can pass that variable as a parameter.
And also, I don't want to create an instance of the class when I declare the variable and then, another instance when I use the constructor. I think I'm wasting resources and CPU time.
Is it possible to declare a variable without instance it?
Use a pointer to delay instantiation. Prefer smart pointers to raw pointers so you don't have to worry about manual memory management.
#include <memory>
std::shared_ptr<MyClass> variable;
// More code
int main(int argc, char **argv)
{
// More code
variable = std::make_shared<MyClass>(0);
// More code
}
Whether you use std::unique_ptr
or std::shared_ptr
depends on what you plan to do with the pointer.
You can use a std::optional
for this:
#include <optional>
std::optional<MyClass> variable; // not initialized
int main() {
if (variable) {
// enters this if only when initialized
}
variable = MyClass(0);
// Access the contained value:
MyClass value = *variable;
int member = variable->member;
}
The std::optional
type is available in C++17. If your project is constrained to an older version, you can always use a polyfill
I am not sure, but it seems like you have created a constructor like :
MyClass(int v) : value(v) {}
and not written the default constructor, which may look like :
MyClass() {}
Because of this, the compiler cannot find the constructor to instantiate a MyClass object when you write:
MyClass variable;
In short, you have to explicitly write the default constructor when you have written other constructors but also want to use the default one.
And your question is a bit vague, when you declare a variable of a class like above, you are indeed creating an instance of it. Even when doing
variable = MyClass(0);
you are creating a temporary object of MyClass and then using the assignment operator to assign it to the variable object.
You could just initialise the variable with some temporary value with the existing constructor when you declare it. Ideally with a value you could easily identify when debugging.
MyClass variable(-1);
Although then it would probably make more sense to just add a default constructor that does that.
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