I don't really think this is possible the way you want it to be,
polymorphism in C++ just doesn't work like this.
If I understood well, you want a variable declared as Base decides,
depending on the parameter type, whether it is going to be Derived1 or
Derived2, all without using the Factory pattern.
The reason why this is not possible is that, the Base
class is not really aware of the existence of its Derived
classes nor you can declare a stack variable and make it "behave" as a derived class. However, I can suggest a work-around but then again, this
doesn't satisfy all the expectations of the real class hierarchy you
want (if you really want it that way_:
class Facade{
public:
Facade(int foo) : b(new Derived1(foo)){}
Facade(bool foo) : b(new Derived2(foo)){}
Base Value()
{
return *b;
}
private:
Base* b;
};
And then you can do something like:
Facade foo(10);
Facade bar(true);
int x = (reinterpret_cast<Derived1*>(foo.Value())) -> val;
bool y = (reinterpret_cast<Derived2*>(bar.Value())) -> val;