简体   繁体   中英

c++: Dynamically choose which subclass to create

I am new to c++ and i have a question.

Lets say we have a base class Base and two derived classes, Derived1 and Derived2. fe Derived1 has a constructor taking a integer and Derived2 a constructor taking a boolean.

Is it possible to determine at run time (or at compile time) which of those two subclasses to create and assign it to the Base class.

Something like this: Base b = ???(value), where value is of type integer or boolean.

Thanks in advance!

Write two overloads of a function called createMyBlaBla . One accepting int , and the other accepting bool . Everyone returns the desired derived class type. eg:

Base* create(int n)
{
    return new Derived1(n);
}
Base* create(bool b)
{
    return new Derived2(b);
}
....
Base* b1 = create(10);    // Derived1
Base* b2 = create(false); // Derived2

People call this the factory pattern.

您可能想要工厂设计模式

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM