struct FOO {
int f;
FOO (int ft) {
f = ft;
}
} jellyfoo ;
int main () {
int x = something that is determined at runtime
jellyfoo(x);
return 0;
}
Of course, jellyfoo's constructor (the default (pretend there is one)) was already called, so I can't call the other one. I want to keep jellyfoo a global variable, but I don't know what x is. Do I HAVE to use a setter? Is there no way to do the Java thing that I know and love:
1 2
Foo jellyfish;
jellyfish = new Foo(x);
There's nothing like that in C++?
EDIT: And if I do have to use a setter, I know there is this handy initializing constructor thing:
FOO (int ft) : f(ft) {}
Or something like that. Is there anything like that that I can use withOUT it being a constructor? As in, just a regular function.
Thanks for the reply! But that's dynamic allocation, right? I'm not sure if that's exactly what I'm looking for. I mean, I think it works, but the only thing I don't know right away is 'x'. I think it would be better to use a setter then. Someone correct me if I'm wrong though.
EDIT: Just to clarify a little bit, I am against using a setter, because I am only going to set 'f' once in the entire program, and that is why it would be nice to have it in the constructor. However, I want other functions to be able to use "jellyfish", not just main().
Yeah, I just don't want to have to use a setter, because I only need to set 'f' once in the entire program, and I would prefer to set it in the constructor. Maybe it's just me being picky about encapsulation and all that.
You can't just call the constructor, the constructor is called specifically when the object is created (and thus is the only thing that can initialize const vars and other things). The closest you could get is to make an init/reset function and call that.