I'm an experienced C and Java programmer already, but I am using C++ for the first time. I am constantly encountering a problem which seems very simple, but I have yet to find an answer elsewhere!
My problem is that a line such as this:
MyClass classvar;
will automatically create a new instance of MyClass, which is different from what I am used to with Java, but manageable. However, this becomes a problem if MyClass does not expose a constructor which requires no arguments (ie MyClass()), as the arguments have to be provided the moment the variable initialises. This is an issue since I am unable to declare a global variable at the top of the source file and initialise it later on when the relevant argument values have also been initialised. Is there any way around this?
I feel like I must be missing something very obvious, so if anyone can help I would be very grateful!
> This an issue since I am unable to declare a global variable at the top of the source file and initialise it later on when the relevant argument values have also been initialised.
Why are you unable to? Does your religion prohibits such an action?
What he means is that he wants to run the constructor for a class, but he doesn't have the data for the constructor until he is already into the main loop. To solve your problem:
Declare a pointer to MyClass. Then once you get the data, use new to create an instance of MyClass for the pointer. Remember to use delete at the end.
Ex:
1 2 3 4 5 6 7 8 9
MyClass* classvar;
int main() {
//get data
classvar = new MyClass(/*args*/);
//do stuff with it
delete classvar;
return 0;
}
Declare a global variable that is a pointer to the class you want. Then, when you get the parameters use new ClassName(/*constructor*/); to initialize it. Just make sure to delete it when you are finished.
Hi everyone, thanks for all your replies. Yes, it was me just being an idiot, it was because I had forgotten to declare it as a pointer and so g++ was trying to initialise it for me. Thats what you get for doing Java for 2 years and then jumping straight into C++!