by DCoder · 16y ago · 0 comments
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... 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();