Coming to C++ with a Java background, I'd like to set up some polymorphic code by initializing a variable of type A
with one of two implementations, B
or C
.
My question is whether there is an easy way to do this on the stack. I have a case where I'm only using A
inside the method body, and want it destroyed at the end of the function, so touching the heap is optional.
Here's how I would do it on the heap:
A* a = NULL;
if (p) {
B* b = new B();
b->setSomethingImplementationSpecific();
a = b;
}
else {
a = new C();
}
doSomething(a);
delete(a);
In practice I'd probably pull this out into a factory method, and use an auto_ptr
to avoid the delete(a)
.
This works, but can I do it on the stack? My thought pattern is something like this:
A* a = NULL;
if (p) {
B b;
b.setSomethingImplementationSpecific();
a = &b;
}
else {
C c;
a = &c;
}
doSomething(a);
Now I don't have to bother with delete(a)
, but doSomething(a)
won't work, since the B
or C
is destroyed when they go out of scope.
I've been trying to figure out a way to do part of it with the ternary operator as well, but I end up both borking up the syntax and taking the address of a temporary -- so am I right that there is no way to do this?
A * const a = &(p ? B() : C());
Advice on whether it's a silly idea to implement polymorphism on the stack in the first place is welcome, but mostly I'm trying to better understand the limits of C/C++ in this area, independently of design sense.