3 ms·
Conditional initialization? Suppose I have several objects of the same type and need to do manipulations on one of them, which one depends on something: Foo
by DCoder 16y ago
Conditional initialization? Suppose I have several objects of the same type and need to do manipulations on one of them, which one depends on something:
Foo * pFoo = NULL;
if(x) {
// stuff
pFoo = Foo::p1;
} else {
// stuff
pFoo = Foo::p2;
}
if(pFoo) {
pFoo->bar();
}
I can't declare pFoo inside if(x) due to scoping, so I have to declare it before initializing it meaningfully. It has to be either a pointer to the object (references don't work without initialization) or an object copy, which would not modify the original object...
- vmathew 16y agoIn the first place, a language that exposes pointers may not be able to do away with null. But as for languages like Java, the problem can be solved with the help of an implicit, non-mutable default object: Foo foo; // initialized to default if (x) { // stuff foo = Foo.p1; } else { // stuff foo = Foo.p2; } // No need to check if this is a valid reference, it always will be. foo.bar();